Edit on GitHub

Expressions

Every AST node in SQLGlot is represented by a subclass of Expression.

This module contains the implementation of all supported Expression types. Additionally, it exposes a number of helper functions, which are mainly used to programmatically build SQL expressions, such as sqlglot.expressions.select.


   1"""
   2## Expressions
   3
   4Every AST node in SQLGlot is represented by a subclass of `Expression`.
   5
   6This module contains the implementation of all supported `Expression` types. Additionally,
   7it exposes a number of helper functions, which are mainly used to programmatically build
   8SQL expressions, such as `sqlglot.expressions.select`.
   9
  10----
  11"""
  12
  13from __future__ import annotations
  14
  15import datetime
  16import math
  17import numbers
  18import re
  19import typing as t
  20from collections import deque
  21from copy import deepcopy
  22from enum import auto
  23
  24from sqlglot.errors import ParseError
  25from sqlglot.helper import (
  26    AutoName,
  27    camel_to_snake_case,
  28    ensure_collection,
  29    seq_get,
  30    split_num_words,
  31    subclasses,
  32)
  33from sqlglot.tokens import Token
  34
  35if t.TYPE_CHECKING:
  36    from sqlglot.dialects.dialect import DialectType
  37
  38E = t.TypeVar("E", bound="Expression")
  39
  40
  41class _Expression(type):
  42    def __new__(cls, clsname, bases, attrs):
  43        klass = super().__new__(cls, clsname, bases, attrs)
  44
  45        # When an Expression class is created, its key is automatically set to be
  46        # the lowercase version of the class' name.
  47        klass.key = clsname.lower()
  48
  49        # This is so that docstrings are not inherited in pdoc
  50        klass.__doc__ = klass.__doc__ or ""
  51
  52        return klass
  53
  54
  55class Expression(metaclass=_Expression):
  56    """
  57    The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
  58    context, such as its child expressions, their names (arg keys), and whether a given child expression
  59    is optional or not.
  60
  61    Attributes:
  62        key: a unique key for each class in the Expression hierarchy. This is useful for hashing
  63            and representing expressions as strings.
  64        arg_types: determines what arguments (child nodes) are supported by an expression. It
  65            maps arg keys to booleans that indicate whether the corresponding args are optional.
  66
  67    Example:
  68        >>> class Foo(Expression):
  69        ...     arg_types = {"this": True, "expression": False}
  70
  71        The above definition informs us that Foo is an Expression that requires an argument called
  72        "this" and may also optionally receive an argument called "expression".
  73
  74    Args:
  75        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
  76        parent: a reference to the parent expression (or None, in case of root expressions).
  77        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
  78            uses to refer to it.
  79        comments: a list of comments that are associated with a given expression. This is used in
  80            order to preserve comments when transpiling SQL code.
  81        _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
  82            optimizer, in order to enable some transformations that require type information.
  83    """
  84
  85    key = "expression"
  86    arg_types = {"this": True}
  87    __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta")
  88
  89    def __init__(self, **args: t.Any):
  90        self.args: t.Dict[str, t.Any] = args
  91        self.parent: t.Optional[Expression] = None
  92        self.arg_key: t.Optional[str] = None
  93        self.comments: t.Optional[t.List[str]] = None
  94        self._type: t.Optional[DataType] = None
  95        self._meta: t.Optional[t.Dict[str, t.Any]] = None
  96
  97        for arg_key, value in self.args.items():
  98            self._set_parent(arg_key, value)
  99
 100    def __eq__(self, other) -> bool:
 101        return type(self) is type(other) and _norm_args(self) == _norm_args(other)
 102
 103    def __hash__(self) -> int:
 104        return hash(
 105            (
 106                self.key,
 107                tuple(
 108                    (k, tuple(v) if isinstance(v, list) else v) for k, v in _norm_args(self).items()
 109                ),
 110            )
 111        )
 112
 113    @property
 114    def this(self):
 115        """
 116        Retrieves the argument with key "this".
 117        """
 118        return self.args.get("this")
 119
 120    @property
 121    def expression(self):
 122        """
 123        Retrieves the argument with key "expression".
 124        """
 125        return self.args.get("expression")
 126
 127    @property
 128    def expressions(self):
 129        """
 130        Retrieves the argument with key "expressions".
 131        """
 132        return self.args.get("expressions") or []
 133
 134    def text(self, key) -> str:
 135        """
 136        Returns a textual representation of the argument corresponding to "key". This can only be used
 137        for args that are strings or leaf Expression instances, such as identifiers and literals.
 138        """
 139        field = self.args.get(key)
 140        if isinstance(field, str):
 141            return field
 142        if isinstance(field, (Identifier, Literal, Var)):
 143            return field.this
 144        if isinstance(field, (Star, Null)):
 145            return field.name
 146        return ""
 147
 148    @property
 149    def is_string(self) -> bool:
 150        """
 151        Checks whether a Literal expression is a string.
 152        """
 153        return isinstance(self, Literal) and self.args["is_string"]
 154
 155    @property
 156    def is_number(self) -> bool:
 157        """
 158        Checks whether a Literal expression is a number.
 159        """
 160        return isinstance(self, Literal) and not self.args["is_string"]
 161
 162    @property
 163    def is_int(self) -> bool:
 164        """
 165        Checks whether a Literal expression is an integer.
 166        """
 167        if self.is_number:
 168            try:
 169                int(self.name)
 170                return True
 171            except ValueError:
 172                pass
 173        return False
 174
 175    @property
 176    def is_star(self) -> bool:
 177        """Checks whether an expression is a star."""
 178        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
 179
 180    @property
 181    def alias(self) -> str:
 182        """
 183        Returns the alias of the expression, or an empty string if it's not aliased.
 184        """
 185        if isinstance(self.args.get("alias"), TableAlias):
 186            return self.args["alias"].name
 187        return self.text("alias")
 188
 189    @property
 190    def name(self) -> str:
 191        return self.text("this")
 192
 193    @property
 194    def alias_or_name(self):
 195        return self.alias or self.name
 196
 197    @property
 198    def output_name(self):
 199        """
 200        Name of the output column if this expression is a selection.
 201
 202        If the Expression has no output name, an empty string is returned.
 203
 204        Example:
 205            >>> from sqlglot import parse_one
 206            >>> parse_one("SELECT a").expressions[0].output_name
 207            'a'
 208            >>> parse_one("SELECT b AS c").expressions[0].output_name
 209            'c'
 210            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
 211            ''
 212        """
 213        return ""
 214
 215    @property
 216    def type(self) -> t.Optional[DataType]:
 217        return self._type
 218
 219    @type.setter
 220    def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None:
 221        if dtype and not isinstance(dtype, DataType):
 222            dtype = DataType.build(dtype)
 223        self._type = dtype  # type: ignore
 224
 225    @property
 226    def meta(self) -> t.Dict[str, t.Any]:
 227        if self._meta is None:
 228            self._meta = {}
 229        return self._meta
 230
 231    def __deepcopy__(self, memo):
 232        copy = self.__class__(**deepcopy(self.args))
 233        if self.comments is not None:
 234            copy.comments = deepcopy(self.comments)
 235
 236        if self._type is not None:
 237            copy._type = self._type.copy()
 238
 239        if self._meta is not None:
 240            copy._meta = deepcopy(self._meta)
 241
 242        return copy
 243
 244    def copy(self):
 245        """
 246        Returns a deep copy of the expression.
 247        """
 248        new = deepcopy(self)
 249        new.parent = self.parent
 250        for item, parent, _ in new.bfs():
 251            if isinstance(item, Expression) and parent:
 252                item.parent = parent
 253        return new
 254
 255    def append(self, arg_key, value):
 256        """
 257        Appends value to arg_key if it's a list or sets it as a new list.
 258
 259        Args:
 260            arg_key (str): name of the list expression arg
 261            value (Any): value to append to the list
 262        """
 263        if not isinstance(self.args.get(arg_key), list):
 264            self.args[arg_key] = []
 265        self.args[arg_key].append(value)
 266        self._set_parent(arg_key, value)
 267
 268    def set(self, arg_key, value):
 269        """
 270        Sets `arg_key` to `value`.
 271
 272        Args:
 273            arg_key (str): name of the expression arg.
 274            value: value to set the arg to.
 275        """
 276        self.args[arg_key] = value
 277        self._set_parent(arg_key, value)
 278
 279    def _set_parent(self, arg_key, value):
 280        if isinstance(value, Expression):
 281            value.parent = self
 282            value.arg_key = arg_key
 283        elif isinstance(value, list):
 284            for v in value:
 285                if isinstance(v, Expression):
 286                    v.parent = self
 287                    v.arg_key = arg_key
 288
 289    @property
 290    def depth(self):
 291        """
 292        Returns the depth of this tree.
 293        """
 294        if self.parent:
 295            return self.parent.depth + 1
 296        return 0
 297
 298    def find(self, *expression_types: t.Type[E], bfs=True) -> E | None:
 299        """
 300        Returns the first node in this tree which matches at least one of
 301        the specified types.
 302
 303        Args:
 304            expression_types: the expression type(s) to match.
 305
 306        Returns:
 307            The node which matches the criteria or None if no such node was found.
 308        """
 309        return next(self.find_all(*expression_types, bfs=bfs), None)
 310
 311    def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]:
 312        """
 313        Returns a generator object which visits all nodes in this tree and only
 314        yields those that match at least one of the specified expression types.
 315
 316        Args:
 317            expression_types: the expression type(s) to match.
 318
 319        Returns:
 320            The generator object.
 321        """
 322        for expression, _, _ in self.walk(bfs=bfs):
 323            if isinstance(expression, expression_types):
 324                yield expression
 325
 326    def find_ancestor(self, *expression_types: t.Type[E]) -> E | None:
 327        """
 328        Returns a nearest parent matching expression_types.
 329
 330        Args:
 331            expression_types: the expression type(s) to match.
 332
 333        Returns:
 334            The parent node.
 335        """
 336        ancestor = self.parent
 337        while ancestor and not isinstance(ancestor, expression_types):
 338            ancestor = ancestor.parent
 339        return t.cast(E, ancestor)
 340
 341    @property
 342    def parent_select(self):
 343        """
 344        Returns the parent select statement.
 345        """
 346        return self.find_ancestor(Select)
 347
 348    def root(self) -> Expression:
 349        """
 350        Returns the root expression of this tree.
 351        """
 352        expression = self
 353        while expression.parent:
 354            expression = expression.parent
 355        return expression
 356
 357    def walk(self, bfs=True, prune=None):
 358        """
 359        Returns a generator object which visits all nodes in this tree.
 360
 361        Args:
 362            bfs (bool): if set to True the BFS traversal order will be applied,
 363                otherwise the DFS traversal will be used instead.
 364            prune ((node, parent, arg_key) -> bool): callable that returns True if
 365                the generator should stop traversing this branch of the tree.
 366
 367        Returns:
 368            the generator object.
 369        """
 370        if bfs:
 371            yield from self.bfs(prune=prune)
 372        else:
 373            yield from self.dfs(prune=prune)
 374
 375    def dfs(self, parent=None, key=None, prune=None):
 376        """
 377        Returns a generator object which visits all nodes in this tree in
 378        the DFS (Depth-first) order.
 379
 380        Returns:
 381            The generator object.
 382        """
 383        parent = parent or self.parent
 384        yield self, parent, key
 385        if prune and prune(self, parent, key):
 386            return
 387
 388        for k, v in self.args.items():
 389            for node in ensure_collection(v):
 390                if isinstance(node, Expression):
 391                    yield from node.dfs(self, k, prune)
 392
 393    def bfs(self, prune=None):
 394        """
 395        Returns a generator object which visits all nodes in this tree in
 396        the BFS (Breadth-first) order.
 397
 398        Returns:
 399            The generator object.
 400        """
 401        queue = deque([(self, self.parent, None)])
 402
 403        while queue:
 404            item, parent, key = queue.popleft()
 405
 406            yield item, parent, key
 407            if prune and prune(item, parent, key):
 408                continue
 409
 410            if isinstance(item, Expression):
 411                for k, v in item.args.items():
 412                    for node in ensure_collection(v):
 413                        if isinstance(node, Expression):
 414                            queue.append((node, item, k))
 415
 416    def unnest(self):
 417        """
 418        Returns the first non parenthesis child or self.
 419        """
 420        expression = self
 421        while isinstance(expression, Paren):
 422            expression = expression.this
 423        return expression
 424
 425    def unalias(self):
 426        """
 427        Returns the inner expression if this is an Alias.
 428        """
 429        if isinstance(self, Alias):
 430            return self.this
 431        return self
 432
 433    def unnest_operands(self):
 434        """
 435        Returns unnested operands as a tuple.
 436        """
 437        return tuple(arg.unnest() for arg in self.args.values() if arg)
 438
 439    def flatten(self, unnest=True):
 440        """
 441        Returns a generator which yields child nodes who's parents are the same class.
 442
 443        A AND B AND C -> [A, B, C]
 444        """
 445        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not isinstance(n, self.__class__)):
 446            if not isinstance(node, self.__class__):
 447                yield node.unnest() if unnest else node
 448
 449    def __str__(self):
 450        return self.sql()
 451
 452    def __repr__(self):
 453        return self._to_s()
 454
 455    def sql(self, dialect: DialectType = None, **opts) -> str:
 456        """
 457        Returns SQL string representation of this tree.
 458
 459        Args:
 460            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
 461            opts: other `sqlglot.generator.Generator` options.
 462
 463        Returns:
 464            The SQL string.
 465        """
 466        from sqlglot.dialects import Dialect
 467
 468        return Dialect.get_or_raise(dialect)().generate(self, **opts)
 469
 470    def _to_s(self, hide_missing: bool = True, level: int = 0) -> str:
 471        indent = "" if not level else "\n"
 472        indent += "".join(["  "] * level)
 473        left = f"({self.key.upper()} "
 474
 475        args: t.Dict[str, t.Any] = {
 476            k: ", ".join(
 477                v._to_s(hide_missing=hide_missing, level=level + 1)
 478                if hasattr(v, "_to_s")
 479                else str(v)
 480                for v in ensure_collection(vs)
 481                if v is not None
 482            )
 483            for k, vs in self.args.items()
 484        }
 485        args["comments"] = self.comments
 486        args["type"] = self.type
 487        args = {k: v for k, v in args.items() if v or not hide_missing}
 488
 489        right = ", ".join(f"{k}: {v}" for k, v in args.items())
 490        right += ")"
 491
 492        return indent + left + right
 493
 494    def transform(self, fun, *args, copy=True, **kwargs):
 495        """
 496        Recursively visits all tree nodes (excluding already transformed ones)
 497        and applies the given transformation function to each node.
 498
 499        Args:
 500            fun (function): a function which takes a node as an argument and returns a
 501                new transformed node or the same node without modifications. If the function
 502                returns None, then the corresponding node will be removed from the syntax tree.
 503            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
 504                modified in place.
 505
 506        Returns:
 507            The transformed tree.
 508        """
 509        node = self.copy() if copy else self
 510        new_node = fun(node, *args, **kwargs)
 511
 512        if new_node is None or not isinstance(new_node, Expression):
 513            return new_node
 514        if new_node is not node:
 515            new_node.parent = node.parent
 516            return new_node
 517
 518        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
 519        return new_node
 520
 521    def replace(self, expression):
 522        """
 523        Swap out this expression with a new expression.
 524
 525        For example::
 526
 527            >>> tree = Select().select("x").from_("tbl")
 528            >>> tree.find(Column).replace(Column(this="y"))
 529            (COLUMN this: y)
 530            >>> tree.sql()
 531            'SELECT y FROM tbl'
 532
 533        Args:
 534            expression (Expression|None): new node
 535
 536        Returns:
 537            The new expression or expressions.
 538        """
 539        if not self.parent:
 540            return expression
 541
 542        parent = self.parent
 543        self.parent = None
 544
 545        replace_children(parent, lambda child: expression if child is self else child)
 546        return expression
 547
 548    def pop(self):
 549        """
 550        Remove this expression from its AST.
 551
 552        Returns:
 553            The popped expression.
 554        """
 555        self.replace(None)
 556        return self
 557
 558    def assert_is(self, type_):
 559        """
 560        Assert that this `Expression` is an instance of `type_`.
 561
 562        If it is NOT an instance of `type_`, this raises an assertion error.
 563        Otherwise, this returns this expression.
 564
 565        Examples:
 566            This is useful for type security in chained expressions:
 567
 568            >>> import sqlglot
 569            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
 570            'SELECT x, z FROM y'
 571        """
 572        assert isinstance(self, type_)
 573        return self
 574
 575    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
 576        """
 577        Checks if this expression is valid (e.g. all mandatory args are set).
 578
 579        Args:
 580            args: a sequence of values that were used to instantiate a Func expression. This is used
 581                to check that the provided arguments don't exceed the function argument limit.
 582
 583        Returns:
 584            A list of error messages for all possible errors that were found.
 585        """
 586        errors: t.List[str] = []
 587
 588        for k in self.args:
 589            if k not in self.arg_types:
 590                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
 591        for k, mandatory in self.arg_types.items():
 592            v = self.args.get(k)
 593            if mandatory and (v is None or (isinstance(v, list) and not v)):
 594                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
 595
 596        if (
 597            args
 598            and isinstance(self, Func)
 599            and len(args) > len(self.arg_types)
 600            and not self.is_var_len_args
 601        ):
 602            errors.append(
 603                f"The number of provided arguments ({len(args)}) is greater than "
 604                f"the maximum number of supported arguments ({len(self.arg_types)})"
 605            )
 606
 607        return errors
 608
 609    def dump(self):
 610        """
 611        Dump this Expression to a JSON-serializable dict.
 612        """
 613        from sqlglot.serde import dump
 614
 615        return dump(self)
 616
 617    @classmethod
 618    def load(cls, obj):
 619        """
 620        Load a dict (as returned by `Expression.dump`) into an Expression instance.
 621        """
 622        from sqlglot.serde import load
 623
 624        return load(obj)
 625
 626
 627IntoType = t.Union[
 628    str,
 629    t.Type[Expression],
 630    t.Collection[t.Union[str, t.Type[Expression]]],
 631]
 632ExpOrStr = t.Union[str, Expression]
 633
 634
 635class Condition(Expression):
 636    def and_(self, *expressions, dialect=None, **opts):
 637        """
 638        AND this condition with one or multiple expressions.
 639
 640        Example:
 641            >>> condition("x=1").and_("y=1").sql()
 642            'x = 1 AND y = 1'
 643
 644        Args:
 645            *expressions (str | Expression): the SQL code strings to parse.
 646                If an `Expression` instance is passed, it will be used as-is.
 647            dialect (str): the dialect used to parse the input expression.
 648            opts (kwargs): other options to use to parse the input expressions.
 649
 650        Returns:
 651            And: the new condition.
 652        """
 653        return and_(self, *expressions, dialect=dialect, **opts)
 654
 655    def or_(self, *expressions, dialect=None, **opts):
 656        """
 657        OR this condition with one or multiple expressions.
 658
 659        Example:
 660            >>> condition("x=1").or_("y=1").sql()
 661            'x = 1 OR y = 1'
 662
 663        Args:
 664            *expressions (str | Expression): the SQL code strings to parse.
 665                If an `Expression` instance is passed, it will be used as-is.
 666            dialect (str): the dialect used to parse the input expression.
 667            opts (kwargs): other options to use to parse the input expressions.
 668
 669        Returns:
 670            Or: the new condition.
 671        """
 672        return or_(self, *expressions, dialect=dialect, **opts)
 673
 674    def not_(self):
 675        """
 676        Wrap this condition with NOT.
 677
 678        Example:
 679            >>> condition("x=1").not_().sql()
 680            'NOT x = 1'
 681
 682        Returns:
 683            Not: the new condition.
 684        """
 685        return not_(self)
 686
 687
 688class Predicate(Condition):
 689    """Relationships like x = y, x > 1, x >= y."""
 690
 691
 692class DerivedTable(Expression):
 693    @property
 694    def alias_column_names(self):
 695        table_alias = self.args.get("alias")
 696        if not table_alias:
 697            return []
 698        column_list = table_alias.assert_is(TableAlias).args.get("columns") or []
 699        return [c.name for c in column_list]
 700
 701    @property
 702    def selects(self):
 703        alias = self.args.get("alias")
 704
 705        if alias:
 706            return alias.columns
 707        return []
 708
 709    @property
 710    def named_selects(self):
 711        return [select.output_name for select in self.selects]
 712
 713
 714class Unionable(Expression):
 715    def union(self, expression, distinct=True, dialect=None, **opts):
 716        """
 717        Builds a UNION expression.
 718
 719        Example:
 720            >>> import sqlglot
 721            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
 722            'SELECT * FROM foo UNION SELECT * FROM bla'
 723
 724        Args:
 725            expression (str | Expression): the SQL code string.
 726                If an `Expression` instance is passed, it will be used as-is.
 727            distinct (bool): set the DISTINCT flag if and only if this is true.
 728            dialect (str): the dialect used to parse the input expression.
 729            opts (kwargs): other options to use to parse the input expressions.
 730        Returns:
 731            Union: the Union expression.
 732        """
 733        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 734
 735    def intersect(self, expression, distinct=True, dialect=None, **opts):
 736        """
 737        Builds an INTERSECT expression.
 738
 739        Example:
 740            >>> import sqlglot
 741            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
 742            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
 743
 744        Args:
 745            expression (str | Expression): the SQL code string.
 746                If an `Expression` instance is passed, it will be used as-is.
 747            distinct (bool): set the DISTINCT flag if and only if this is true.
 748            dialect (str): the dialect used to parse the input expression.
 749            opts (kwargs): other options to use to parse the input expressions.
 750        Returns:
 751            Intersect: the Intersect expression
 752        """
 753        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 754
 755    def except_(self, expression, distinct=True, dialect=None, **opts):
 756        """
 757        Builds an EXCEPT expression.
 758
 759        Example:
 760            >>> import sqlglot
 761            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
 762            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
 763
 764        Args:
 765            expression (str | Expression): the SQL code string.
 766                If an `Expression` instance is passed, it will be used as-is.
 767            distinct (bool): set the DISTINCT flag if and only if this is true.
 768            dialect (str): the dialect used to parse the input expression.
 769            opts (kwargs): other options to use to parse the input expressions.
 770        Returns:
 771            Except: the Except expression
 772        """
 773        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 774
 775
 776class UDTF(DerivedTable, Unionable):
 777    pass
 778
 779
 780class Cache(Expression):
 781    arg_types = {
 782        "with": False,
 783        "this": True,
 784        "lazy": False,
 785        "options": False,
 786        "expression": False,
 787    }
 788
 789
 790class Uncache(Expression):
 791    arg_types = {"this": True, "exists": False}
 792
 793
 794class Create(Expression):
 795    arg_types = {
 796        "with": False,
 797        "this": True,
 798        "kind": True,
 799        "expression": False,
 800        "exists": False,
 801        "properties": False,
 802        "replace": False,
 803        "unique": False,
 804        "volatile": False,
 805        "indexes": False,
 806        "no_schema_binding": False,
 807        "begin": False,
 808    }
 809
 810
 811class Describe(Expression):
 812    arg_types = {"this": True, "kind": False}
 813
 814
 815class Set(Expression):
 816    arg_types = {"expressions": False}
 817
 818
 819class SetItem(Expression):
 820    arg_types = {
 821        "this": False,
 822        "expressions": False,
 823        "kind": False,
 824        "collate": False,  # MySQL SET NAMES statement
 825        "global": False,
 826    }
 827
 828
 829class Show(Expression):
 830    arg_types = {
 831        "this": True,
 832        "target": False,
 833        "offset": False,
 834        "limit": False,
 835        "like": False,
 836        "where": False,
 837        "db": False,
 838        "full": False,
 839        "mutex": False,
 840        "query": False,
 841        "channel": False,
 842        "global": False,
 843        "log": False,
 844        "position": False,
 845        "types": False,
 846    }
 847
 848
 849class UserDefinedFunction(Expression):
 850    arg_types = {"this": True, "expressions": False, "wrapped": False}
 851
 852
 853class CharacterSet(Expression):
 854    arg_types = {"this": True, "default": False}
 855
 856
 857class With(Expression):
 858    arg_types = {"expressions": True, "recursive": False}
 859
 860    @property
 861    def recursive(self) -> bool:
 862        return bool(self.args.get("recursive"))
 863
 864
 865class WithinGroup(Expression):
 866    arg_types = {"this": True, "expression": False}
 867
 868
 869class CTE(DerivedTable):
 870    arg_types = {"this": True, "alias": True}
 871
 872
 873class TableAlias(Expression):
 874    arg_types = {"this": False, "columns": False}
 875
 876    @property
 877    def columns(self):
 878        return self.args.get("columns") or []
 879
 880
 881class BitString(Condition):
 882    pass
 883
 884
 885class HexString(Condition):
 886    pass
 887
 888
 889class ByteString(Condition):
 890    pass
 891
 892
 893class Column(Condition):
 894    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
 895
 896    @property
 897    def table(self) -> str:
 898        return self.text("table")
 899
 900    @property
 901    def db(self) -> str:
 902        return self.text("db")
 903
 904    @property
 905    def catalog(self) -> str:
 906        return self.text("catalog")
 907
 908    @property
 909    def output_name(self) -> str:
 910        return self.name
 911
 912    @property
 913    def parts(self) -> t.List[Identifier]:
 914        """Return the parts of a column in order catalog, db, table, name."""
 915        return [part for part in reversed(list(self.args.values())) if part]
 916
 917    def to_dot(self) -> Dot:
 918        """Converts the column into a dot expression."""
 919        parts = self.parts
 920        parent = self.parent
 921
 922        while parent:
 923            if isinstance(parent, Dot):
 924                parts.append(parent.expression)
 925            parent = parent.parent
 926
 927        return Dot.build(parts)
 928
 929
 930class ColumnDef(Expression):
 931    arg_types = {
 932        "this": True,
 933        "kind": False,
 934        "constraints": False,
 935        "exists": False,
 936    }
 937
 938
 939class AlterColumn(Expression):
 940    arg_types = {
 941        "this": True,
 942        "dtype": False,
 943        "collate": False,
 944        "using": False,
 945        "default": False,
 946        "drop": False,
 947    }
 948
 949
 950class RenameTable(Expression):
 951    pass
 952
 953
 954class SetTag(Expression):
 955    arg_types = {"expressions": True, "unset": False}
 956
 957
 958class Comment(Expression):
 959    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
 960
 961
 962class ColumnConstraint(Expression):
 963    arg_types = {"this": False, "kind": True}
 964
 965
 966class ColumnConstraintKind(Expression):
 967    pass
 968
 969
 970class AutoIncrementColumnConstraint(ColumnConstraintKind):
 971    pass
 972
 973
 974class CaseSpecificColumnConstraint(ColumnConstraintKind):
 975    arg_types = {"not_": True}
 976
 977
 978class CharacterSetColumnConstraint(ColumnConstraintKind):
 979    arg_types = {"this": True}
 980
 981
 982class CheckColumnConstraint(ColumnConstraintKind):
 983    pass
 984
 985
 986class CollateColumnConstraint(ColumnConstraintKind):
 987    pass
 988
 989
 990class CommentColumnConstraint(ColumnConstraintKind):
 991    pass
 992
 993
 994class CompressColumnConstraint(ColumnConstraintKind):
 995    pass
 996
 997
 998class DateFormatColumnConstraint(ColumnConstraintKind):
 999    arg_types = {"this": True}
1000
1001
1002class DefaultColumnConstraint(ColumnConstraintKind):
1003    pass
1004
1005
1006class EncodeColumnConstraint(ColumnConstraintKind):
1007    pass
1008
1009
1010class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1011    # this: True -> ALWAYS, this: False -> BY DEFAULT
1012    arg_types = {
1013        "this": False,
1014        "start": False,
1015        "increment": False,
1016        "minvalue": False,
1017        "maxvalue": False,
1018        "cycle": False,
1019    }
1020
1021
1022class InlineLengthColumnConstraint(ColumnConstraintKind):
1023    pass
1024
1025
1026class NotNullColumnConstraint(ColumnConstraintKind):
1027    arg_types = {"allow_null": False}
1028
1029
1030class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1031    arg_types = {"desc": False}
1032
1033
1034class TitleColumnConstraint(ColumnConstraintKind):
1035    pass
1036
1037
1038class UniqueColumnConstraint(ColumnConstraintKind):
1039    arg_types: t.Dict[str, t.Any] = {}
1040
1041
1042class UppercaseColumnConstraint(ColumnConstraintKind):
1043    arg_types: t.Dict[str, t.Any] = {}
1044
1045
1046class PathColumnConstraint(ColumnConstraintKind):
1047    pass
1048
1049
1050class Constraint(Expression):
1051    arg_types = {"this": True, "expressions": True}
1052
1053
1054class Delete(Expression):
1055    arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False}
1056
1057    def delete(
1058        self,
1059        table: ExpOrStr,
1060        dialect: DialectType = None,
1061        copy: bool = True,
1062        **opts,
1063    ) -> Delete:
1064        """
1065        Create a DELETE expression or replace the table on an existing DELETE expression.
1066
1067        Example:
1068            >>> delete("tbl").sql()
1069            'DELETE FROM tbl'
1070
1071        Args:
1072            table: the table from which to delete.
1073            dialect: the dialect used to parse the input expression.
1074            copy: if `False`, modify this expression instance in-place.
1075            opts: other options to use to parse the input expressions.
1076
1077        Returns:
1078            Delete: the modified expression.
1079        """
1080        return _apply_builder(
1081            expression=table,
1082            instance=self,
1083            arg="this",
1084            dialect=dialect,
1085            into=Table,
1086            copy=copy,
1087            **opts,
1088        )
1089
1090    def where(
1091        self,
1092        *expressions: ExpOrStr,
1093        append: bool = True,
1094        dialect: DialectType = None,
1095        copy: bool = True,
1096        **opts,
1097    ) -> Delete:
1098        """
1099        Append to or set the WHERE expressions.
1100
1101        Example:
1102            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1103            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1104
1105        Args:
1106            *expressions: the SQL code strings to parse.
1107                If an `Expression` instance is passed, it will be used as-is.
1108                Multiple expressions are combined with an AND operator.
1109            append: if `True`, AND the new expressions to any existing expression.
1110                Otherwise, this resets the expression.
1111            dialect: the dialect used to parse the input expressions.
1112            copy: if `False`, modify this expression instance in-place.
1113            opts: other options to use to parse the input expressions.
1114
1115        Returns:
1116            Delete: the modified expression.
1117        """
1118        return _apply_conjunction_builder(
1119            *expressions,
1120            instance=self,
1121            arg="where",
1122            append=append,
1123            into=Where,
1124            dialect=dialect,
1125            copy=copy,
1126            **opts,
1127        )
1128
1129    def returning(
1130        self,
1131        expression: ExpOrStr,
1132        dialect: DialectType = None,
1133        copy: bool = True,
1134        **opts,
1135    ) -> Delete:
1136        """
1137        Set the RETURNING expression. Not supported by all dialects.
1138
1139        Example:
1140            >>> delete("tbl").returning("*", dialect="postgres").sql()
1141            'DELETE FROM tbl RETURNING *'
1142
1143        Args:
1144            expression: the SQL code strings to parse.
1145                If an `Expression` instance is passed, it will be used as-is.
1146            dialect: the dialect used to parse the input expressions.
1147            copy: if `False`, modify this expression instance in-place.
1148            opts: other options to use to parse the input expressions.
1149
1150        Returns:
1151            Delete: the modified expression.
1152        """
1153        return _apply_builder(
1154            expression=expression,
1155            instance=self,
1156            arg="returning",
1157            prefix="RETURNING",
1158            dialect=dialect,
1159            copy=copy,
1160            into=Returning,
1161            **opts,
1162        )
1163
1164
1165class Drop(Expression):
1166    arg_types = {
1167        "this": False,
1168        "kind": False,
1169        "exists": False,
1170        "temporary": False,
1171        "materialized": False,
1172        "cascade": False,
1173    }
1174
1175
1176class Filter(Expression):
1177    arg_types = {"this": True, "expression": True}
1178
1179
1180class Check(Expression):
1181    pass
1182
1183
1184class Directory(Expression):
1185    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1186    arg_types = {"this": True, "local": False, "row_format": False}
1187
1188
1189class ForeignKey(Expression):
1190    arg_types = {
1191        "expressions": True,
1192        "reference": False,
1193        "delete": False,
1194        "update": False,
1195    }
1196
1197
1198class PrimaryKey(Expression):
1199    arg_types = {"expressions": True, "options": False}
1200
1201
1202class Unique(Expression):
1203    arg_types = {"expressions": True}
1204
1205
1206# https://www.postgresql.org/docs/9.1/sql-selectinto.html
1207# https://docs.aws.amazon.com/redshift/latest/dg/r_SELECT_INTO.html#r_SELECT_INTO-examples
1208class Into(Expression):
1209    arg_types = {"this": True, "temporary": False, "unlogged": False}
1210
1211
1212class From(Expression):
1213    arg_types = {"expressions": True}
1214
1215
1216class Having(Expression):
1217    pass
1218
1219
1220class Hint(Expression):
1221    arg_types = {"expressions": True}
1222
1223
1224class JoinHint(Expression):
1225    arg_types = {"this": True, "expressions": True}
1226
1227
1228class Identifier(Expression):
1229    arg_types = {"this": True, "quoted": False}
1230
1231    @property
1232    def quoted(self):
1233        return bool(self.args.get("quoted"))
1234
1235    def __eq__(self, other):
1236        return isinstance(other, self.__class__) and _norm_arg(self.this) == _norm_arg(other.this)
1237
1238    def __hash__(self):
1239        return hash((self.key, self.this.lower()))
1240
1241    @property
1242    def output_name(self):
1243        return self.name
1244
1245
1246class Index(Expression):
1247    arg_types = {
1248        "this": False,
1249        "table": False,
1250        "where": False,
1251        "columns": False,
1252        "unique": False,
1253        "primary": False,
1254        "amp": False,  # teradata
1255    }
1256
1257
1258class Insert(Expression):
1259    arg_types = {
1260        "with": False,
1261        "this": True,
1262        "expression": False,
1263        "returning": False,
1264        "overwrite": False,
1265        "exists": False,
1266        "partition": False,
1267        "alternative": False,
1268    }
1269
1270
1271class Returning(Expression):
1272    arg_types = {"expressions": True}
1273
1274
1275# https://dev.mysql.com/doc/refman/8.0/en/charset-introducer.html
1276class Introducer(Expression):
1277    arg_types = {"this": True, "expression": True}
1278
1279
1280# national char, like n'utf8'
1281class National(Expression):
1282    pass
1283
1284
1285class LoadData(Expression):
1286    arg_types = {
1287        "this": True,
1288        "local": False,
1289        "overwrite": False,
1290        "inpath": True,
1291        "partition": False,
1292        "input_format": False,
1293        "serde": False,
1294    }
1295
1296
1297class Partition(Expression):
1298    arg_types = {"expressions": True}
1299
1300
1301class Fetch(Expression):
1302    arg_types = {"direction": False, "count": False}
1303
1304
1305class Group(Expression):
1306    arg_types = {
1307        "expressions": False,
1308        "grouping_sets": False,
1309        "cube": False,
1310        "rollup": False,
1311    }
1312
1313
1314class Lambda(Expression):
1315    arg_types = {"this": True, "expressions": True}
1316
1317
1318class Limit(Expression):
1319    arg_types = {"this": False, "expression": True}
1320
1321
1322class Literal(Condition):
1323    arg_types = {"this": True, "is_string": True}
1324
1325    def __eq__(self, other):
1326        return (
1327            isinstance(other, Literal)
1328            and self.this == other.this
1329            and self.args["is_string"] == other.args["is_string"]
1330        )
1331
1332    def __hash__(self):
1333        return hash((self.key, self.this, self.args["is_string"]))
1334
1335    @classmethod
1336    def number(cls, number) -> Literal:
1337        return cls(this=str(number), is_string=False)
1338
1339    @classmethod
1340    def string(cls, string) -> Literal:
1341        return cls(this=str(string), is_string=True)
1342
1343    @property
1344    def output_name(self):
1345        return self.name
1346
1347
1348class Join(Expression):
1349    arg_types = {
1350        "this": True,
1351        "on": False,
1352        "side": False,
1353        "kind": False,
1354        "using": False,
1355        "natural": False,
1356    }
1357
1358    @property
1359    def kind(self):
1360        return self.text("kind").upper()
1361
1362    @property
1363    def side(self):
1364        return self.text("side").upper()
1365
1366    @property
1367    def alias_or_name(self):
1368        return self.this.alias_or_name
1369
1370    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1371        """
1372        Append to or set the ON expressions.
1373
1374        Example:
1375            >>> import sqlglot
1376            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1377            'JOIN x ON y = 1'
1378
1379        Args:
1380            *expressions (str | Expression): the SQL code strings to parse.
1381                If an `Expression` instance is passed, it will be used as-is.
1382                Multiple expressions are combined with an AND operator.
1383            append (bool): if `True`, AND the new expressions to any existing expression.
1384                Otherwise, this resets the expression.
1385            dialect (str): the dialect used to parse the input expressions.
1386            copy (bool): if `False`, modify this expression instance in-place.
1387            opts (kwargs): other options to use to parse the input expressions.
1388
1389        Returns:
1390            Join: the modified join expression.
1391        """
1392        join = _apply_conjunction_builder(
1393            *expressions,
1394            instance=self,
1395            arg="on",
1396            append=append,
1397            dialect=dialect,
1398            copy=copy,
1399            **opts,
1400        )
1401
1402        if join.kind == "CROSS":
1403            join.set("kind", None)
1404
1405        return join
1406
1407    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1408        """
1409        Append to or set the USING expressions.
1410
1411        Example:
1412            >>> import sqlglot
1413            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1414            'JOIN x USING (foo, bla)'
1415
1416        Args:
1417            *expressions (str | Expression): the SQL code strings to parse.
1418                If an `Expression` instance is passed, it will be used as-is.
1419            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1420                Otherwise, this resets the expression.
1421            dialect (str): the dialect used to parse the input expressions.
1422            copy (bool): if `False`, modify this expression instance in-place.
1423            opts (kwargs): other options to use to parse the input expressions.
1424
1425        Returns:
1426            Join: the modified join expression.
1427        """
1428        join = _apply_list_builder(
1429            *expressions,
1430            instance=self,
1431            arg="using",
1432            append=append,
1433            dialect=dialect,
1434            copy=copy,
1435            **opts,
1436        )
1437
1438        if join.kind == "CROSS":
1439            join.set("kind", None)
1440
1441        return join
1442
1443
1444class Lateral(UDTF):
1445    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
1446
1447
1448class MatchRecognize(Expression):
1449    arg_types = {
1450        "partition_by": False,
1451        "order": False,
1452        "measures": False,
1453        "rows": False,
1454        "after": False,
1455        "pattern": False,
1456        "define": False,
1457    }
1458
1459
1460# Clickhouse FROM FINAL modifier
1461# https://clickhouse.com/docs/en/sql-reference/statements/select/from/#final-modifier
1462class Final(Expression):
1463    pass
1464
1465
1466class Offset(Expression):
1467    arg_types = {"this": False, "expression": True}
1468
1469
1470class Order(Expression):
1471    arg_types = {"this": False, "expressions": True}
1472
1473
1474# hive specific sorts
1475# https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SortBy
1476class Cluster(Order):
1477    pass
1478
1479
1480class Distribute(Order):
1481    pass
1482
1483
1484class Sort(Order):
1485    pass
1486
1487
1488class Ordered(Expression):
1489    arg_types = {"this": True, "desc": True, "nulls_first": True}
1490
1491
1492class Property(Expression):
1493    arg_types = {"this": True, "value": True}
1494
1495
1496class AfterJournalProperty(Property):
1497    arg_types = {"no": True, "dual": False, "local": False}
1498
1499
1500class AlgorithmProperty(Property):
1501    arg_types = {"this": True}
1502
1503
1504class AutoIncrementProperty(Property):
1505    arg_types = {"this": True}
1506
1507
1508class BlockCompressionProperty(Property):
1509    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
1510
1511
1512class CharacterSetProperty(Property):
1513    arg_types = {"this": True, "default": True}
1514
1515
1516class ChecksumProperty(Property):
1517    arg_types = {"on": False, "default": False}
1518
1519
1520class CollateProperty(Property):
1521    arg_types = {"this": True}
1522
1523
1524class DataBlocksizeProperty(Property):
1525    arg_types = {"size": False, "units": False, "min": False, "default": False}
1526
1527
1528class DefinerProperty(Property):
1529    arg_types = {"this": True}
1530
1531
1532class DistKeyProperty(Property):
1533    arg_types = {"this": True}
1534
1535
1536class DistStyleProperty(Property):
1537    arg_types = {"this": True}
1538
1539
1540class EngineProperty(Property):
1541    arg_types = {"this": True}
1542
1543
1544class ExecuteAsProperty(Property):
1545    arg_types = {"this": True}
1546
1547
1548class ExternalProperty(Property):
1549    arg_types = {"this": False}
1550
1551
1552class FallbackProperty(Property):
1553    arg_types = {"no": True, "protection": False}
1554
1555
1556class FileFormatProperty(Property):
1557    arg_types = {"this": True}
1558
1559
1560class FreespaceProperty(Property):
1561    arg_types = {"this": True, "percent": False}
1562
1563
1564class IsolatedLoadingProperty(Property):
1565    arg_types = {
1566        "no": True,
1567        "concurrent": True,
1568        "for_all": True,
1569        "for_insert": True,
1570        "for_none": True,
1571    }
1572
1573
1574class JournalProperty(Property):
1575    arg_types = {"no": True, "dual": False, "before": False}
1576
1577
1578class LanguageProperty(Property):
1579    arg_types = {"this": True}
1580
1581
1582class LikeProperty(Property):
1583    arg_types = {"this": True, "expressions": False}
1584
1585
1586class LocationProperty(Property):
1587    arg_types = {"this": True}
1588
1589
1590class LockingProperty(Property):
1591    arg_types = {
1592        "this": False,
1593        "kind": True,
1594        "for_or_in": True,
1595        "lock_type": True,
1596        "override": False,
1597    }
1598
1599
1600class LogProperty(Property):
1601    arg_types = {"no": True}
1602
1603
1604class MaterializedProperty(Property):
1605    arg_types = {"this": False}
1606
1607
1608class MergeBlockRatioProperty(Property):
1609    arg_types = {"this": False, "no": False, "default": False, "percent": False}
1610
1611
1612class NoPrimaryIndexProperty(Property):
1613    arg_types = {"this": False}
1614
1615
1616class OnCommitProperty(Property):
1617    arg_type = {"this": False}
1618
1619
1620class PartitionedByProperty(Property):
1621    arg_types = {"this": True}
1622
1623
1624class ReturnsProperty(Property):
1625    arg_types = {"this": True, "is_table": False, "table": False}
1626
1627
1628class RowFormatDelimitedProperty(Property):
1629    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
1630    arg_types = {
1631        "fields": False,
1632        "escaped": False,
1633        "collection_items": False,
1634        "map_keys": False,
1635        "lines": False,
1636        "null": False,
1637        "serde": False,
1638    }
1639
1640
1641class RowFormatSerdeProperty(Property):
1642    arg_types = {"this": True}
1643
1644
1645class SchemaCommentProperty(Property):
1646    arg_types = {"this": True}
1647
1648
1649class SerdeProperties(Property):
1650    arg_types = {"expressions": True}
1651
1652
1653class SetProperty(Property):
1654    arg_types = {"multi": True}
1655
1656
1657class SortKeyProperty(Property):
1658    arg_types = {"this": True, "compound": False}
1659
1660
1661class SqlSecurityProperty(Property):
1662    arg_types = {"definer": True}
1663
1664
1665class TableFormatProperty(Property):
1666    arg_types = {"this": True}
1667
1668
1669class TemporaryProperty(Property):
1670    arg_types = {"global_": True}
1671
1672
1673class TransientProperty(Property):
1674    arg_types = {"this": False}
1675
1676
1677class VolatilityProperty(Property):
1678    arg_types = {"this": True}
1679
1680
1681class WithDataProperty(Property):
1682    arg_types = {"no": True, "statistics": False}
1683
1684
1685class WithJournalTableProperty(Property):
1686    arg_types = {"this": True}
1687
1688
1689class Properties(Expression):
1690    arg_types = {"expressions": True}
1691
1692    NAME_TO_PROPERTY = {
1693        "ALGORITHM": AlgorithmProperty,
1694        "AUTO_INCREMENT": AutoIncrementProperty,
1695        "CHARACTER SET": CharacterSetProperty,
1696        "COLLATE": CollateProperty,
1697        "COMMENT": SchemaCommentProperty,
1698        "DEFINER": DefinerProperty,
1699        "DISTKEY": DistKeyProperty,
1700        "DISTSTYLE": DistStyleProperty,
1701        "ENGINE": EngineProperty,
1702        "EXECUTE AS": ExecuteAsProperty,
1703        "FORMAT": FileFormatProperty,
1704        "LANGUAGE": LanguageProperty,
1705        "LOCATION": LocationProperty,
1706        "PARTITIONED_BY": PartitionedByProperty,
1707        "RETURNS": ReturnsProperty,
1708        "SORTKEY": SortKeyProperty,
1709        "TABLE_FORMAT": TableFormatProperty,
1710    }
1711
1712    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
1713
1714    # CREATE property locations
1715    # Form: schema specified
1716    #   create [POST_CREATE]
1717    #     table a [POST_NAME]
1718    #     (b int) [POST_SCHEMA]
1719    #     with ([POST_WITH])
1720    #     index (b) [POST_INDEX]
1721    #
1722    # Form: alias selection
1723    #   create [POST_CREATE]
1724    #     table a [POST_NAME]
1725    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
1726    #     index (c) [POST_INDEX]
1727    class Location(AutoName):
1728        POST_CREATE = auto()
1729        POST_NAME = auto()
1730        POST_SCHEMA = auto()
1731        POST_WITH = auto()
1732        POST_ALIAS = auto()
1733        POST_EXPRESSION = auto()
1734        POST_INDEX = auto()
1735        UNSUPPORTED = auto()
1736
1737    @classmethod
1738    def from_dict(cls, properties_dict) -> Properties:
1739        expressions = []
1740        for key, value in properties_dict.items():
1741            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1742            if property_cls:
1743                expressions.append(property_cls(this=convert(value)))
1744            else:
1745                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1746
1747        return cls(expressions=expressions)
1748
1749
1750class Qualify(Expression):
1751    pass
1752
1753
1754# https://www.ibm.com/docs/en/ias?topic=procedures-return-statement-in-sql
1755class Return(Expression):
1756    pass
1757
1758
1759class Reference(Expression):
1760    arg_types = {"this": True, "expressions": False, "options": False}
1761
1762
1763class Tuple(Expression):
1764    arg_types = {"expressions": False}
1765
1766
1767class Subqueryable(Unionable):
1768    def subquery(self, alias=None, copy=True) -> Subquery:
1769        """
1770        Convert this expression to an aliased expression that can be used as a Subquery.
1771
1772        Example:
1773            >>> subquery = Select().select("x").from_("tbl").subquery()
1774            >>> Select().select("x").from_(subquery).sql()
1775            'SELECT x FROM (SELECT x FROM tbl)'
1776
1777        Args:
1778            alias (str | Identifier): an optional alias for the subquery
1779            copy (bool): if `False`, modify this expression instance in-place.
1780
1781        Returns:
1782            Alias: the subquery
1783        """
1784        instance = _maybe_copy(self, copy)
1785        return Subquery(
1786            this=instance,
1787            alias=TableAlias(this=to_identifier(alias)),
1788        )
1789
1790    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1791        raise NotImplementedError
1792
1793    @property
1794    def ctes(self):
1795        with_ = self.args.get("with")
1796        if not with_:
1797            return []
1798        return with_.expressions
1799
1800    @property
1801    def selects(self):
1802        raise NotImplementedError("Subqueryable objects must implement `selects`")
1803
1804    @property
1805    def named_selects(self):
1806        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
1807
1808    def with_(
1809        self,
1810        alias,
1811        as_,
1812        recursive=None,
1813        append=True,
1814        dialect=None,
1815        copy=True,
1816        **opts,
1817    ):
1818        """
1819        Append to or set the common table expressions.
1820
1821        Example:
1822            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
1823            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
1824
1825        Args:
1826            alias (str | Expression): the SQL code string to parse as the table name.
1827                If an `Expression` instance is passed, this is used as-is.
1828            as_ (str | Expression): the SQL code string to parse as the table expression.
1829                If an `Expression` instance is passed, it will be used as-is.
1830            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
1831            append (bool): if `True`, add to any existing expressions.
1832                Otherwise, this resets the expressions.
1833            dialect (str): the dialect used to parse the input expression.
1834            copy (bool): if `False`, modify this expression instance in-place.
1835            opts (kwargs): other options to use to parse the input expressions.
1836
1837        Returns:
1838            Select: the modified expression.
1839        """
1840        alias_expression = maybe_parse(
1841            alias,
1842            dialect=dialect,
1843            into=TableAlias,
1844            **opts,
1845        )
1846        as_expression = maybe_parse(
1847            as_,
1848            dialect=dialect,
1849            **opts,
1850        )
1851        cte = CTE(
1852            this=as_expression,
1853            alias=alias_expression,
1854        )
1855        return _apply_child_list_builder(
1856            cte,
1857            instance=self,
1858            arg="with",
1859            append=append,
1860            copy=copy,
1861            into=With,
1862            properties={"recursive": recursive or False},
1863        )
1864
1865
1866QUERY_MODIFIERS = {
1867    "match": False,
1868    "laterals": False,
1869    "joins": False,
1870    "pivots": False,
1871    "where": False,
1872    "group": False,
1873    "having": False,
1874    "qualify": False,
1875    "windows": False,
1876    "distribute": False,
1877    "sort": False,
1878    "cluster": False,
1879    "order": False,
1880    "limit": False,
1881    "offset": False,
1882    "lock": False,
1883    "sample": False,
1884}
1885
1886
1887class Table(Expression):
1888    arg_types = {
1889        "this": True,
1890        "alias": False,
1891        "db": False,
1892        "catalog": False,
1893        "laterals": False,
1894        "joins": False,
1895        "pivots": False,
1896        "hints": False,
1897        "system_time": False,
1898    }
1899
1900    @property
1901    def db(self) -> str:
1902        return self.text("db")
1903
1904    @property
1905    def catalog(self) -> str:
1906        return self.text("catalog")
1907
1908
1909# See the TSQL "Querying data in a system-versioned temporal table" page
1910class SystemTime(Expression):
1911    arg_types = {
1912        "this": False,
1913        "expression": False,
1914        "kind": True,
1915    }
1916
1917
1918class Union(Subqueryable):
1919    arg_types = {
1920        "with": False,
1921        "this": True,
1922        "expression": True,
1923        "distinct": False,
1924        **QUERY_MODIFIERS,
1925    }
1926
1927    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1928        """
1929        Set the LIMIT expression.
1930
1931        Example:
1932            >>> select("1").union(select("1")).limit(1).sql()
1933            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
1934
1935        Args:
1936            expression (str | int | Expression): the SQL code string to parse.
1937                This can also be an integer.
1938                If a `Limit` instance is passed, this is used as-is.
1939                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
1940            dialect (str): the dialect used to parse the input expression.
1941            copy (bool): if `False`, modify this expression instance in-place.
1942            opts (kwargs): other options to use to parse the input expressions.
1943
1944        Returns:
1945            Select: The limited subqueryable.
1946        """
1947        return (
1948            select("*")
1949            .from_(self.subquery(alias="_l_0", copy=copy))
1950            .limit(expression, dialect=dialect, copy=False, **opts)
1951        )
1952
1953    def select(
1954        self,
1955        *expressions: ExpOrStr,
1956        append: bool = True,
1957        dialect: DialectType = None,
1958        copy: bool = True,
1959        **opts,
1960    ) -> Union:
1961        """Append to or set the SELECT of the union recursively.
1962
1963        Example:
1964            >>> from sqlglot import parse_one
1965            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
1966            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
1967
1968        Args:
1969            *expressions: the SQL code strings to parse.
1970                If an `Expression` instance is passed, it will be used as-is.
1971            append: if `True`, add to any existing expressions.
1972                Otherwise, this resets the expressions.
1973            dialect: the dialect used to parse the input expressions.
1974            copy: if `False`, modify this expression instance in-place.
1975            opts: other options to use to parse the input expressions.
1976
1977        Returns:
1978            Union: the modified expression.
1979        """
1980        this = self.copy() if copy else self
1981        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
1982        this.expression.unnest().select(
1983            *expressions, append=append, dialect=dialect, copy=False, **opts
1984        )
1985        return this
1986
1987    @property
1988    def named_selects(self):
1989        return self.this.unnest().named_selects
1990
1991    @property
1992    def is_star(self) -> bool:
1993        return self.this.is_star or self.expression.is_star
1994
1995    @property
1996    def selects(self):
1997        return self.this.unnest().selects
1998
1999    @property
2000    def left(self):
2001        return self.this
2002
2003    @property
2004    def right(self):
2005        return self.expression
2006
2007
2008class Except(Union):
2009    pass
2010
2011
2012class Intersect(Union):
2013    pass
2014
2015
2016class Unnest(UDTF):
2017    arg_types = {
2018        "expressions": True,
2019        "ordinality": False,
2020        "alias": False,
2021        "offset": False,
2022    }
2023
2024
2025class Update(Expression):
2026    arg_types = {
2027        "with": False,
2028        "this": False,
2029        "expressions": True,
2030        "from": False,
2031        "where": False,
2032        "returning": False,
2033    }
2034
2035
2036class Values(UDTF):
2037    arg_types = {
2038        "expressions": True,
2039        "ordinality": False,
2040        "alias": False,
2041    }
2042
2043
2044class Var(Expression):
2045    pass
2046
2047
2048class Schema(Expression):
2049    arg_types = {"this": False, "expressions": False}
2050
2051
2052# Used to represent the FOR UPDATE and FOR SHARE locking read types.
2053# https://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html
2054class Lock(Expression):
2055    arg_types = {"update": True}
2056
2057
2058class Select(Subqueryable):
2059    arg_types = {
2060        "with": False,
2061        "expressions": False,
2062        "hint": False,
2063        "distinct": False,
2064        "into": False,
2065        "from": False,
2066        **QUERY_MODIFIERS,
2067    }
2068
2069    def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2070        """
2071        Set the FROM expression.
2072
2073        Example:
2074            >>> Select().from_("tbl").select("x").sql()
2075            'SELECT x FROM tbl'
2076
2077        Args:
2078            *expressions (str | Expression): the SQL code strings to parse.
2079                If a `From` instance is passed, this is used as-is.
2080                If another `Expression` instance is passed, it will be wrapped in a `From`.
2081            append (bool): if `True`, add to any existing expressions.
2082                Otherwise, this flattens all the `From` expression into a single expression.
2083            dialect (str): the dialect used to parse the input expression.
2084            copy (bool): if `False`, modify this expression instance in-place.
2085            opts (kwargs): other options to use to parse the input expressions.
2086
2087        Returns:
2088            Select: the modified expression.
2089        """
2090        return _apply_child_list_builder(
2091            *expressions,
2092            instance=self,
2093            arg="from",
2094            append=append,
2095            copy=copy,
2096            prefix="FROM",
2097            into=From,
2098            dialect=dialect,
2099            **opts,
2100        )
2101
2102    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2103        """
2104        Set the GROUP BY expression.
2105
2106        Example:
2107            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2108            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2109
2110        Args:
2111            *expressions (str | Expression): the SQL code strings to parse.
2112                If a `Group` instance is passed, this is used as-is.
2113                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2114                If nothing is passed in then a group by is not applied to the expression
2115            append (bool): if `True`, add to any existing expressions.
2116                Otherwise, this flattens all the `Group` expression into a single expression.
2117            dialect (str): the dialect used to parse the input expression.
2118            copy (bool): if `False`, modify this expression instance in-place.
2119            opts (kwargs): other options to use to parse the input expressions.
2120
2121        Returns:
2122            Select: the modified expression.
2123        """
2124        if not expressions:
2125            return self if not copy else self.copy()
2126        return _apply_child_list_builder(
2127            *expressions,
2128            instance=self,
2129            arg="group",
2130            append=append,
2131            copy=copy,
2132            prefix="GROUP BY",
2133            into=Group,
2134            dialect=dialect,
2135            **opts,
2136        )
2137
2138    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2139        """
2140        Set the ORDER BY expression.
2141
2142        Example:
2143            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2144            'SELECT x FROM tbl ORDER BY x DESC'
2145
2146        Args:
2147            *expressions (str | Expression): the SQL code strings to parse.
2148                If a `Group` instance is passed, this is used as-is.
2149                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2150            append (bool): if `True`, add to any existing expressions.
2151                Otherwise, this flattens all the `Order` expression into a single expression.
2152            dialect (str): the dialect used to parse the input expression.
2153            copy (bool): if `False`, modify this expression instance in-place.
2154            opts (kwargs): other options to use to parse the input expressions.
2155
2156        Returns:
2157            Select: the modified expression.
2158        """
2159        return _apply_child_list_builder(
2160            *expressions,
2161            instance=self,
2162            arg="order",
2163            append=append,
2164            copy=copy,
2165            prefix="ORDER BY",
2166            into=Order,
2167            dialect=dialect,
2168            **opts,
2169        )
2170
2171    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2172        """
2173        Set the SORT BY expression.
2174
2175        Example:
2176            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
2177            'SELECT x FROM tbl SORT BY x DESC'
2178
2179        Args:
2180            *expressions (str | Expression): the SQL code strings to parse.
2181                If a `Group` instance is passed, this is used as-is.
2182                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2183            append (bool): if `True`, add to any existing expressions.
2184                Otherwise, this flattens all the `Order` expression into a single expression.
2185            dialect (str): the dialect used to parse the input expression.
2186            copy (bool): if `False`, modify this expression instance in-place.
2187            opts (kwargs): other options to use to parse the input expressions.
2188
2189        Returns:
2190            Select: the modified expression.
2191        """
2192        return _apply_child_list_builder(
2193            *expressions,
2194            instance=self,
2195            arg="sort",
2196            append=append,
2197            copy=copy,
2198            prefix="SORT BY",
2199            into=Sort,
2200            dialect=dialect,
2201            **opts,
2202        )
2203
2204    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2205        """
2206        Set the CLUSTER BY expression.
2207
2208        Example:
2209            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
2210            'SELECT x FROM tbl CLUSTER BY x DESC'
2211
2212        Args:
2213            *expressions (str | Expression): the SQL code strings to parse.
2214                If a `Group` instance is passed, this is used as-is.
2215                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2216            append (bool): if `True`, add to any existing expressions.
2217                Otherwise, this flattens all the `Order` expression into a single expression.
2218            dialect (str): the dialect used to parse the input expression.
2219            copy (bool): if `False`, modify this expression instance in-place.
2220            opts (kwargs): other options to use to parse the input expressions.
2221
2222        Returns:
2223            Select: the modified expression.
2224        """
2225        return _apply_child_list_builder(
2226            *expressions,
2227            instance=self,
2228            arg="cluster",
2229            append=append,
2230            copy=copy,
2231            prefix="CLUSTER BY",
2232            into=Cluster,
2233            dialect=dialect,
2234            **opts,
2235        )
2236
2237    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2238        """
2239        Set the LIMIT expression.
2240
2241        Example:
2242            >>> Select().from_("tbl").select("x").limit(10).sql()
2243            'SELECT x FROM tbl LIMIT 10'
2244
2245        Args:
2246            expression (str | int | Expression): the SQL code string to parse.
2247                This can also be an integer.
2248                If a `Limit` instance is passed, this is used as-is.
2249                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2250            dialect (str): the dialect used to parse the input expression.
2251            copy (bool): if `False`, modify this expression instance in-place.
2252            opts (kwargs): other options to use to parse the input expressions.
2253
2254        Returns:
2255            Select: the modified expression.
2256        """
2257        return _apply_builder(
2258            expression=expression,
2259            instance=self,
2260            arg="limit",
2261            into=Limit,
2262            prefix="LIMIT",
2263            dialect=dialect,
2264            copy=copy,
2265            **opts,
2266        )
2267
2268    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2269        """
2270        Set the OFFSET expression.
2271
2272        Example:
2273            >>> Select().from_("tbl").select("x").offset(10).sql()
2274            'SELECT x FROM tbl OFFSET 10'
2275
2276        Args:
2277            expression (str | int | Expression): the SQL code string to parse.
2278                This can also be an integer.
2279                If a `Offset` instance is passed, this is used as-is.
2280                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2281            dialect (str): the dialect used to parse the input expression.
2282            copy (bool): if `False`, modify this expression instance in-place.
2283            opts (kwargs): other options to use to parse the input expressions.
2284
2285        Returns:
2286            Select: the modified expression.
2287        """
2288        return _apply_builder(
2289            expression=expression,
2290            instance=self,
2291            arg="offset",
2292            into=Offset,
2293            prefix="OFFSET",
2294            dialect=dialect,
2295            copy=copy,
2296            **opts,
2297        )
2298
2299    def select(
2300        self,
2301        *expressions: ExpOrStr,
2302        append: bool = True,
2303        dialect: DialectType = None,
2304        copy: bool = True,
2305        **opts,
2306    ) -> Select:
2307        """
2308        Append to or set the SELECT expressions.
2309
2310        Example:
2311            >>> Select().select("x", "y").sql()
2312            'SELECT x, y'
2313
2314        Args:
2315            *expressions: the SQL code strings to parse.
2316                If an `Expression` instance is passed, it will be used as-is.
2317            append: if `True`, add to any existing expressions.
2318                Otherwise, this resets the expressions.
2319            dialect: the dialect used to parse the input expressions.
2320            copy: if `False`, modify this expression instance in-place.
2321            opts: other options to use to parse the input expressions.
2322
2323        Returns:
2324            Select: the modified expression.
2325        """
2326        return _apply_list_builder(
2327            *expressions,
2328            instance=self,
2329            arg="expressions",
2330            append=append,
2331            dialect=dialect,
2332            copy=copy,
2333            **opts,
2334        )
2335
2336    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2337        """
2338        Append to or set the LATERAL expressions.
2339
2340        Example:
2341            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2342            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2343
2344        Args:
2345            *expressions (str | Expression): the SQL code strings to parse.
2346                If an `Expression` instance is passed, it will be used as-is.
2347            append (bool): if `True`, add to any existing expressions.
2348                Otherwise, this resets the expressions.
2349            dialect (str): the dialect used to parse the input expressions.
2350            copy (bool): if `False`, modify this expression instance in-place.
2351            opts (kwargs): other options to use to parse the input expressions.
2352
2353        Returns:
2354            Select: the modified expression.
2355        """
2356        return _apply_list_builder(
2357            *expressions,
2358            instance=self,
2359            arg="laterals",
2360            append=append,
2361            into=Lateral,
2362            prefix="LATERAL VIEW",
2363            dialect=dialect,
2364            copy=copy,
2365            **opts,
2366        )
2367
2368    def join(
2369        self,
2370        expression,
2371        on=None,
2372        using=None,
2373        append=True,
2374        join_type=None,
2375        join_alias=None,
2376        dialect=None,
2377        copy=True,
2378        **opts,
2379    ) -> Select:
2380        """
2381        Append to or set the JOIN expressions.
2382
2383        Example:
2384            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2385            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2386
2387            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2388            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2389
2390            Use `join_type` to change the type of join:
2391
2392            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2393            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2394
2395        Args:
2396            expression (str | Expression): the SQL code string to parse.
2397                If an `Expression` instance is passed, it will be used as-is.
2398            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2399                If an `Expression` instance is passed, it will be used as-is.
2400            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2401                If an `Expression` instance is passed, it will be used as-is.
2402            append (bool): if `True`, add to any existing expressions.
2403                Otherwise, this resets the expressions.
2404            join_type (str): If set, alter the parsed join type
2405            dialect (str): the dialect used to parse the input expressions.
2406            copy (bool): if `False`, modify this expression instance in-place.
2407            opts (kwargs): other options to use to parse the input expressions.
2408
2409        Returns:
2410            Select: the modified expression.
2411        """
2412        parse_args = {"dialect": dialect, **opts}
2413
2414        try:
2415            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2416        except ParseError:
2417            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2418
2419        join = expression if isinstance(expression, Join) else Join(this=expression)
2420
2421        if isinstance(join.this, Select):
2422            join.this.replace(join.this.subquery())
2423
2424        if join_type:
2425            natural: t.Optional[Token]
2426            side: t.Optional[Token]
2427            kind: t.Optional[Token]
2428
2429            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2430
2431            if natural:
2432                join.set("natural", True)
2433            if side:
2434                join.set("side", side.text)
2435            if kind:
2436                join.set("kind", kind.text)
2437
2438        if on:
2439            on = and_(*ensure_collection(on), dialect=dialect, **opts)
2440            join.set("on", on)
2441
2442        if using:
2443            join = _apply_list_builder(
2444                *ensure_collection(using),
2445                instance=join,
2446                arg="using",
2447                append=append,
2448                copy=copy,
2449                **opts,
2450            )
2451
2452        if join_alias:
2453            join.set("this", alias_(join.this, join_alias, table=True))
2454        return _apply_list_builder(
2455            join,
2456            instance=self,
2457            arg="joins",
2458            append=append,
2459            copy=copy,
2460            **opts,
2461        )
2462
2463    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2464        """
2465        Append to or set the WHERE expressions.
2466
2467        Example:
2468            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2469            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2470
2471        Args:
2472            *expressions (str | Expression): the SQL code strings to parse.
2473                If an `Expression` instance is passed, it will be used as-is.
2474                Multiple expressions are combined with an AND operator.
2475            append (bool): if `True`, AND the new expressions to any existing expression.
2476                Otherwise, this resets the expression.
2477            dialect (str): the dialect used to parse the input expressions.
2478            copy (bool): if `False`, modify this expression instance in-place.
2479            opts (kwargs): other options to use to parse the input expressions.
2480
2481        Returns:
2482            Select: the modified expression.
2483        """
2484        return _apply_conjunction_builder(
2485            *expressions,
2486            instance=self,
2487            arg="where",
2488            append=append,
2489            into=Where,
2490            dialect=dialect,
2491            copy=copy,
2492            **opts,
2493        )
2494
2495    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2496        """
2497        Append to or set the HAVING expressions.
2498
2499        Example:
2500            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2501            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2502
2503        Args:
2504            *expressions (str | Expression): the SQL code strings to parse.
2505                If an `Expression` instance is passed, it will be used as-is.
2506                Multiple expressions are combined with an AND operator.
2507            append (bool): if `True`, AND the new expressions to any existing expression.
2508                Otherwise, this resets the expression.
2509            dialect (str): the dialect used to parse the input expressions.
2510            copy (bool): if `False`, modify this expression instance in-place.
2511            opts (kwargs): other options to use to parse the input expressions.
2512
2513        Returns:
2514            Select: the modified expression.
2515        """
2516        return _apply_conjunction_builder(
2517            *expressions,
2518            instance=self,
2519            arg="having",
2520            append=append,
2521            into=Having,
2522            dialect=dialect,
2523            copy=copy,
2524            **opts,
2525        )
2526
2527    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2528        return _apply_list_builder(
2529            *expressions,
2530            instance=self,
2531            arg="windows",
2532            append=append,
2533            into=Window,
2534            dialect=dialect,
2535            copy=copy,
2536            **opts,
2537        )
2538
2539    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2540        return _apply_conjunction_builder(
2541            *expressions,
2542            instance=self,
2543            arg="qualify",
2544            append=append,
2545            into=Qualify,
2546            dialect=dialect,
2547            copy=copy,
2548            **opts,
2549        )
2550
2551    def distinct(self, distinct=True, copy=True) -> Select:
2552        """
2553        Set the OFFSET expression.
2554
2555        Example:
2556            >>> Select().from_("tbl").select("x").distinct().sql()
2557            'SELECT DISTINCT x FROM tbl'
2558
2559        Args:
2560            distinct (bool): whether the Select should be distinct
2561            copy (bool): if `False`, modify this expression instance in-place.
2562
2563        Returns:
2564            Select: the modified expression.
2565        """
2566        instance = _maybe_copy(self, copy)
2567        instance.set("distinct", Distinct() if distinct else None)
2568        return instance
2569
2570    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2571        """
2572        Convert this expression to a CREATE TABLE AS statement.
2573
2574        Example:
2575            >>> Select().select("*").from_("tbl").ctas("x").sql()
2576            'CREATE TABLE x AS SELECT * FROM tbl'
2577
2578        Args:
2579            table (str | Expression): the SQL code string to parse as the table name.
2580                If another `Expression` instance is passed, it will be used as-is.
2581            properties (dict): an optional mapping of table properties
2582            dialect (str): the dialect used to parse the input table.
2583            copy (bool): if `False`, modify this expression instance in-place.
2584            opts (kwargs): other options to use to parse the input table.
2585
2586        Returns:
2587            Create: the CREATE TABLE AS expression
2588        """
2589        instance = _maybe_copy(self, copy)
2590        table_expression = maybe_parse(
2591            table,
2592            into=Table,
2593            dialect=dialect,
2594            **opts,
2595        )
2596        properties_expression = None
2597        if properties:
2598            properties_expression = Properties.from_dict(properties)
2599
2600        return Create(
2601            this=table_expression,
2602            kind="table",
2603            expression=instance,
2604            properties=properties_expression,
2605        )
2606
2607    def lock(self, update: bool = True, copy: bool = True) -> Select:
2608        """
2609        Set the locking read mode for this expression.
2610
2611        Examples:
2612            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2613            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2614
2615            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2616            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2617
2618        Args:
2619            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2620            copy: if `False`, modify this expression instance in-place.
2621
2622        Returns:
2623            The modified expression.
2624        """
2625
2626        inst = _maybe_copy(self, copy)
2627        inst.set("lock", Lock(update=update))
2628
2629        return inst
2630
2631    @property
2632    def named_selects(self) -> t.List[str]:
2633        return [e.output_name for e in self.expressions if e.alias_or_name]
2634
2635    @property
2636    def is_star(self) -> bool:
2637        return any(expression.is_star for expression in self.expressions)
2638
2639    @property
2640    def selects(self) -> t.List[Expression]:
2641        return self.expressions
2642
2643
2644class Subquery(DerivedTable, Unionable):
2645    arg_types = {
2646        "this": True,
2647        "alias": False,
2648        "with": False,
2649        **QUERY_MODIFIERS,
2650    }
2651
2652    def unnest(self):
2653        """
2654        Returns the first non subquery.
2655        """
2656        expression = self
2657        while isinstance(expression, Subquery):
2658            expression = expression.this
2659        return expression
2660
2661    @property
2662    def is_star(self) -> bool:
2663        return self.this.is_star
2664
2665    @property
2666    def output_name(self):
2667        return self.alias
2668
2669
2670class TableSample(Expression):
2671    arg_types = {
2672        "this": False,
2673        "method": False,
2674        "bucket_numerator": False,
2675        "bucket_denominator": False,
2676        "bucket_field": False,
2677        "percent": False,
2678        "rows": False,
2679        "size": False,
2680        "seed": False,
2681        "kind": False,
2682    }
2683
2684
2685class Tag(Expression):
2686    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
2687
2688    arg_types = {
2689        "this": False,
2690        "prefix": False,
2691        "postfix": False,
2692    }
2693
2694
2695class Pivot(Expression):
2696    arg_types = {
2697        "this": False,
2698        "alias": False,
2699        "expressions": True,
2700        "field": True,
2701        "unpivot": True,
2702    }
2703
2704
2705class Window(Expression):
2706    arg_types = {
2707        "this": True,
2708        "partition_by": False,
2709        "order": False,
2710        "spec": False,
2711        "alias": False,
2712    }
2713
2714
2715class WindowSpec(Expression):
2716    arg_types = {
2717        "kind": False,
2718        "start": False,
2719        "start_side": False,
2720        "end": False,
2721        "end_side": False,
2722    }
2723
2724
2725class Where(Expression):
2726    pass
2727
2728
2729class Star(Expression):
2730    arg_types = {"except": False, "replace": False}
2731
2732    @property
2733    def name(self) -> str:
2734        return "*"
2735
2736    @property
2737    def output_name(self):
2738        return self.name
2739
2740
2741class Parameter(Expression):
2742    arg_types = {"this": True, "wrapped": False}
2743
2744
2745class SessionParameter(Expression):
2746    arg_types = {"this": True, "kind": False}
2747
2748
2749class Placeholder(Expression):
2750    arg_types = {"this": False}
2751
2752
2753class Null(Condition):
2754    arg_types: t.Dict[str, t.Any] = {}
2755
2756    @property
2757    def name(self) -> str:
2758        return "NULL"
2759
2760
2761class Boolean(Condition):
2762    pass
2763
2764
2765class DataType(Expression):
2766    arg_types = {
2767        "this": True,
2768        "expressions": False,
2769        "nested": False,
2770        "values": False,
2771        "prefix": False,
2772    }
2773
2774    class Type(AutoName):
2775        CHAR = auto()
2776        NCHAR = auto()
2777        VARCHAR = auto()
2778        NVARCHAR = auto()
2779        TEXT = auto()
2780        MEDIUMTEXT = auto()
2781        LONGTEXT = auto()
2782        MEDIUMBLOB = auto()
2783        LONGBLOB = auto()
2784        BINARY = auto()
2785        VARBINARY = auto()
2786        INT = auto()
2787        UINT = auto()
2788        TINYINT = auto()
2789        UTINYINT = auto()
2790        SMALLINT = auto()
2791        USMALLINT = auto()
2792        BIGINT = auto()
2793        UBIGINT = auto()
2794        FLOAT = auto()
2795        DOUBLE = auto()
2796        DECIMAL = auto()
2797        BIT = auto()
2798        BOOLEAN = auto()
2799        JSON = auto()
2800        JSONB = auto()
2801        INTERVAL = auto()
2802        TIME = auto()
2803        TIMESTAMP = auto()
2804        TIMESTAMPTZ = auto()
2805        TIMESTAMPLTZ = auto()
2806        DATE = auto()
2807        DATETIME = auto()
2808        ARRAY = auto()
2809        MAP = auto()
2810        UUID = auto()
2811        GEOGRAPHY = auto()
2812        GEOMETRY = auto()
2813        STRUCT = auto()
2814        NULLABLE = auto()
2815        HLLSKETCH = auto()
2816        HSTORE = auto()
2817        SUPER = auto()
2818        SERIAL = auto()
2819        SMALLSERIAL = auto()
2820        BIGSERIAL = auto()
2821        XML = auto()
2822        UNIQUEIDENTIFIER = auto()
2823        MONEY = auto()
2824        SMALLMONEY = auto()
2825        ROWVERSION = auto()
2826        IMAGE = auto()
2827        VARIANT = auto()
2828        OBJECT = auto()
2829        INET = auto()
2830        NULL = auto()
2831        UNKNOWN = auto()  # Sentinel value, useful for type annotation
2832
2833    TEXT_TYPES = {
2834        Type.CHAR,
2835        Type.NCHAR,
2836        Type.VARCHAR,
2837        Type.NVARCHAR,
2838        Type.TEXT,
2839    }
2840
2841    INTEGER_TYPES = {
2842        Type.INT,
2843        Type.TINYINT,
2844        Type.SMALLINT,
2845        Type.BIGINT,
2846    }
2847
2848    FLOAT_TYPES = {
2849        Type.FLOAT,
2850        Type.DOUBLE,
2851    }
2852
2853    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
2854
2855    TEMPORAL_TYPES = {
2856        Type.TIMESTAMP,
2857        Type.TIMESTAMPTZ,
2858        Type.TIMESTAMPLTZ,
2859        Type.DATE,
2860        Type.DATETIME,
2861    }
2862
2863    @classmethod
2864    def build(
2865        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
2866    ) -> DataType:
2867        from sqlglot import parse_one
2868
2869        if isinstance(dtype, str):
2870            if dtype.upper() in cls.Type.__members__:
2871                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
2872            else:
2873                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
2874            if data_type_exp is None:
2875                raise ValueError(f"Unparsable data type value: {dtype}")
2876        elif isinstance(dtype, DataType.Type):
2877            data_type_exp = DataType(this=dtype)
2878        elif isinstance(dtype, DataType):
2879            return dtype
2880        else:
2881            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
2882        return DataType(**{**data_type_exp.args, **kwargs})
2883
2884    def is_type(self, dtype: DataType.Type) -> bool:
2885        return self.this == dtype
2886
2887
2888# https://www.postgresql.org/docs/15/datatype-pseudo.html
2889class PseudoType(Expression):
2890    pass
2891
2892
2893class StructKwarg(Expression):
2894    arg_types = {"this": True, "expression": True}
2895
2896
2897# WHERE x <OP> EXISTS|ALL|ANY|SOME(SELECT ...)
2898class SubqueryPredicate(Predicate):
2899    pass
2900
2901
2902class All(SubqueryPredicate):
2903    pass
2904
2905
2906class Any(SubqueryPredicate):
2907    pass
2908
2909
2910class Exists(SubqueryPredicate):
2911    pass
2912
2913
2914# Commands to interact with the databases or engines. For most of the command
2915# expressions we parse whatever comes after the command's name as a string.
2916class Command(Expression):
2917    arg_types = {"this": True, "expression": False}
2918
2919
2920class Transaction(Expression):
2921    arg_types = {"this": False, "modes": False}
2922
2923
2924class Commit(Expression):
2925    arg_types = {"chain": False}
2926
2927
2928class Rollback(Expression):
2929    arg_types = {"savepoint": False}
2930
2931
2932class AlterTable(Expression):
2933    arg_types = {"this": True, "actions": True, "exists": False}
2934
2935
2936class AddConstraint(Expression):
2937    arg_types = {"this": False, "expression": False, "enforced": False}
2938
2939
2940class DropPartition(Expression):
2941    arg_types = {"expressions": True, "exists": False}
2942
2943
2944# Binary expressions like (ADD a b)
2945class Binary(Expression):
2946    arg_types = {"this": True, "expression": True}
2947
2948    @property
2949    def left(self):
2950        return self.this
2951
2952    @property
2953    def right(self):
2954        return self.expression
2955
2956
2957class Add(Binary):
2958    pass
2959
2960
2961class Connector(Binary, Condition):
2962    pass
2963
2964
2965class And(Connector):
2966    pass
2967
2968
2969class Or(Connector):
2970    pass
2971
2972
2973class BitwiseAnd(Binary):
2974    pass
2975
2976
2977class BitwiseLeftShift(Binary):
2978    pass
2979
2980
2981class BitwiseOr(Binary):
2982    pass
2983
2984
2985class BitwiseRightShift(Binary):
2986    pass
2987
2988
2989class BitwiseXor(Binary):
2990    pass
2991
2992
2993class Div(Binary):
2994    pass
2995
2996
2997class Overlaps(Binary):
2998    pass
2999
3000
3001class Dot(Binary):
3002    @property
3003    def name(self) -> str:
3004        return self.expression.name
3005
3006    @classmethod
3007    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3008        """Build a Dot object with a sequence of expressions."""
3009        if len(expressions) < 2:
3010            raise ValueError(f"Dot requires >= 2 expressions.")
3011
3012        a, b, *expressions = expressions
3013        dot = Dot(this=a, expression=b)
3014
3015        for expression in expressions:
3016            dot = Dot(this=dot, expression=expression)
3017
3018        return dot
3019
3020
3021class DPipe(Binary):
3022    pass
3023
3024
3025class EQ(Binary, Predicate):
3026    pass
3027
3028
3029class NullSafeEQ(Binary, Predicate):
3030    pass
3031
3032
3033class NullSafeNEQ(Binary, Predicate):
3034    pass
3035
3036
3037class Distance(Binary):
3038    pass
3039
3040
3041class Escape(Binary):
3042    pass
3043
3044
3045class Glob(Binary, Predicate):
3046    pass
3047
3048
3049class GT(Binary, Predicate):
3050    pass
3051
3052
3053class GTE(Binary, Predicate):
3054    pass
3055
3056
3057class ILike(Binary, Predicate):
3058    pass
3059
3060
3061class ILikeAny(Binary, Predicate):
3062    pass
3063
3064
3065class IntDiv(Binary):
3066    pass
3067
3068
3069class Is(Binary, Predicate):
3070    pass
3071
3072
3073class Kwarg(Binary):
3074    """Kwarg in special functions like func(kwarg => y)."""
3075
3076
3077class Like(Binary, Predicate):
3078    pass
3079
3080
3081class LikeAny(Binary, Predicate):
3082    pass
3083
3084
3085class LT(Binary, Predicate):
3086    pass
3087
3088
3089class LTE(Binary, Predicate):
3090    pass
3091
3092
3093class Mod(Binary):
3094    pass
3095
3096
3097class Mul(Binary):
3098    pass
3099
3100
3101class NEQ(Binary, Predicate):
3102    pass
3103
3104
3105class SimilarTo(Binary, Predicate):
3106    pass
3107
3108
3109class Slice(Binary):
3110    arg_types = {"this": False, "expression": False}
3111
3112
3113class Sub(Binary):
3114    pass
3115
3116
3117class ArrayOverlaps(Binary):
3118    pass
3119
3120
3121# Unary Expressions
3122# (NOT a)
3123class Unary(Expression):
3124    pass
3125
3126
3127class BitwiseNot(Unary):
3128    pass
3129
3130
3131class Not(Unary, Condition):
3132    pass
3133
3134
3135class Paren(Unary, Condition):
3136    arg_types = {"this": True, "with": False}
3137
3138
3139class Neg(Unary):
3140    pass
3141
3142
3143# Special Functions
3144class Alias(Expression):
3145    arg_types = {"this": True, "alias": False}
3146
3147    @property
3148    def output_name(self):
3149        return self.alias
3150
3151
3152class Aliases(Expression):
3153    arg_types = {"this": True, "expressions": True}
3154
3155    @property
3156    def aliases(self):
3157        return self.expressions
3158
3159
3160class AtTimeZone(Expression):
3161    arg_types = {"this": True, "zone": True}
3162
3163
3164class Between(Predicate):
3165    arg_types = {"this": True, "low": True, "high": True}
3166
3167
3168class Bracket(Condition):
3169    arg_types = {"this": True, "expressions": True}
3170
3171
3172class Distinct(Expression):
3173    arg_types = {"expressions": False, "on": False}
3174
3175
3176class In(Predicate):
3177    arg_types = {
3178        "this": True,
3179        "expressions": False,
3180        "query": False,
3181        "unnest": False,
3182        "field": False,
3183        "is_global": False,
3184    }
3185
3186
3187class TimeUnit(Expression):
3188    """Automatically converts unit arg into a var."""
3189
3190    arg_types = {"unit": False}
3191
3192    def __init__(self, **args):
3193        unit = args.get("unit")
3194        if isinstance(unit, (Column, Literal)):
3195            args["unit"] = Var(this=unit.name)
3196        elif isinstance(unit, Week):
3197            unit.set("this", Var(this=unit.this.name))
3198        super().__init__(**args)
3199
3200
3201class Interval(TimeUnit):
3202    arg_types = {"this": False, "unit": False}
3203
3204
3205class IgnoreNulls(Expression):
3206    pass
3207
3208
3209class RespectNulls(Expression):
3210    pass
3211
3212
3213# Functions
3214class Func(Condition):
3215    """
3216    The base class for all function expressions.
3217
3218    Attributes:
3219        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3220            treated as a variable length argument and the argument's value will be stored as a list.
3221        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3222            for this function expression. These values are used to map this node to a name during parsing
3223            as well as to provide the function's name during SQL string generation. By default the SQL
3224            name is set to the expression's class name transformed to snake case.
3225    """
3226
3227    is_var_len_args = False
3228
3229    @classmethod
3230    def from_arg_list(cls, args):
3231        if cls.is_var_len_args:
3232            all_arg_keys = list(cls.arg_types)
3233            # If this function supports variable length argument treat the last argument as such.
3234            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3235            num_non_var = len(non_var_len_arg_keys)
3236
3237            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3238            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3239        else:
3240            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3241
3242        return cls(**args_dict)
3243
3244    @classmethod
3245    def sql_names(cls):
3246        if cls is Func:
3247            raise NotImplementedError(
3248                "SQL name is only supported by concrete function implementations"
3249            )
3250        if "_sql_names" not in cls.__dict__:
3251            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3252        return cls._sql_names
3253
3254    @classmethod
3255    def sql_name(cls):
3256        return cls.sql_names()[0]
3257
3258    @classmethod
3259    def default_parser_mappings(cls):
3260        return {name: cls.from_arg_list for name in cls.sql_names()}
3261
3262
3263class AggFunc(Func):
3264    pass
3265
3266
3267class Abs(Func):
3268    pass
3269
3270
3271class Anonymous(Func):
3272    arg_types = {"this": True, "expressions": False}
3273    is_var_len_args = True
3274
3275
3276class ApproxDistinct(AggFunc):
3277    arg_types = {"this": True, "accuracy": False}
3278
3279
3280class Array(Func):
3281    arg_types = {"expressions": False}
3282    is_var_len_args = True
3283
3284
3285# https://docs.snowflake.com/en/sql-reference/functions/to_char
3286class ToChar(Func):
3287    arg_types = {"this": True, "format": False}
3288
3289
3290class GenerateSeries(Func):
3291    arg_types = {"start": True, "end": True, "step": False}
3292
3293
3294class ArrayAgg(AggFunc):
3295    pass
3296
3297
3298class ArrayAll(Func):
3299    arg_types = {"this": True, "expression": True}
3300
3301
3302class ArrayAny(Func):
3303    arg_types = {"this": True, "expression": True}
3304
3305
3306class ArrayConcat(Func):
3307    arg_types = {"this": True, "expressions": False}
3308    is_var_len_args = True
3309
3310
3311class ArrayContains(Binary, Func):
3312    pass
3313
3314
3315class ArrayContained(Binary):
3316    pass
3317
3318
3319class ArrayFilter(Func):
3320    arg_types = {"this": True, "expression": True}
3321    _sql_names = ["FILTER", "ARRAY_FILTER"]
3322
3323
3324class ArrayJoin(Func):
3325    arg_types = {"this": True, "expression": True, "null": False}
3326
3327
3328class ArraySize(Func):
3329    arg_types = {"this": True, "expression": False}
3330
3331
3332class ArraySort(Func):
3333    arg_types = {"this": True, "expression": False}
3334
3335
3336class ArraySum(Func):
3337    pass
3338
3339
3340class ArrayUnionAgg(AggFunc):
3341    pass
3342
3343
3344class Avg(AggFunc):
3345    pass
3346
3347
3348class AnyValue(AggFunc):
3349    pass
3350
3351
3352class Case(Func):
3353    arg_types = {"this": False, "ifs": True, "default": False}
3354
3355
3356class Cast(Func):
3357    arg_types = {"this": True, "to": True}
3358
3359    @property
3360    def name(self) -> str:
3361        return self.this.name
3362
3363    @property
3364    def to(self):
3365        return self.args["to"]
3366
3367    @property
3368    def output_name(self):
3369        return self.name
3370
3371    def is_type(self, dtype: DataType.Type) -> bool:
3372        return self.to.is_type(dtype)
3373
3374
3375class Collate(Binary):
3376    pass
3377
3378
3379class TryCast(Cast):
3380    pass
3381
3382
3383class Ceil(Func):
3384    arg_types = {"this": True, "decimals": False}
3385    _sql_names = ["CEIL", "CEILING"]
3386
3387
3388class Coalesce(Func):
3389    arg_types = {"this": True, "expressions": False}
3390    is_var_len_args = True
3391
3392
3393class Concat(Func):
3394    arg_types = {"expressions": True}
3395    is_var_len_args = True
3396
3397
3398class ConcatWs(Concat):
3399    _sql_names = ["CONCAT_WS"]
3400
3401
3402class Count(AggFunc):
3403    arg_types = {"this": False}
3404
3405
3406class CountIf(AggFunc):
3407    pass
3408
3409
3410class CurrentDate(Func):
3411    arg_types = {"this": False}
3412
3413
3414class CurrentDatetime(Func):
3415    arg_types = {"this": False}
3416
3417
3418class CurrentTime(Func):
3419    arg_types = {"this": False}
3420
3421
3422class CurrentTimestamp(Func):
3423    arg_types = {"this": False}
3424
3425
3426class DateAdd(Func, TimeUnit):
3427    arg_types = {"this": True, "expression": True, "unit": False}
3428
3429
3430class DateSub(Func, TimeUnit):
3431    arg_types = {"this": True, "expression": True, "unit": False}
3432
3433
3434class DateDiff(Func, TimeUnit):
3435    _sql_names = ["DATEDIFF", "DATE_DIFF"]
3436    arg_types = {"this": True, "expression": True, "unit": False}
3437
3438
3439class DateTrunc(Func):
3440    arg_types = {"unit": True, "this": True, "zone": False}
3441
3442
3443class DatetimeAdd(Func, TimeUnit):
3444    arg_types = {"this": True, "expression": True, "unit": False}
3445
3446
3447class DatetimeSub(Func, TimeUnit):
3448    arg_types = {"this": True, "expression": True, "unit": False}
3449
3450
3451class DatetimeDiff(Func, TimeUnit):
3452    arg_types = {"this": True, "expression": True, "unit": False}
3453
3454
3455class DatetimeTrunc(Func, TimeUnit):
3456    arg_types = {"this": True, "unit": True, "zone": False}
3457
3458
3459class DayOfWeek(Func):
3460    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
3461
3462
3463class DayOfMonth(Func):
3464    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
3465
3466
3467class DayOfYear(Func):
3468    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
3469
3470
3471class WeekOfYear(Func):
3472    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
3473
3474
3475class LastDateOfMonth(Func):
3476    pass
3477
3478
3479class Extract(Func):
3480    arg_types = {"this": True, "expression": True}
3481
3482
3483class TimestampAdd(Func, TimeUnit):
3484    arg_types = {"this": True, "expression": True, "unit": False}
3485
3486
3487class TimestampSub(Func, TimeUnit):
3488    arg_types = {"this": True, "expression": True, "unit": False}
3489
3490
3491class TimestampDiff(Func, TimeUnit):
3492    arg_types = {"this": True, "expression": True, "unit": False}
3493
3494
3495class TimestampTrunc(Func, TimeUnit):
3496    arg_types = {"this": True, "unit": True, "zone": False}
3497
3498
3499class TimeAdd(Func, TimeUnit):
3500    arg_types = {"this": True, "expression": True, "unit": False}
3501
3502
3503class TimeSub(Func, TimeUnit):
3504    arg_types = {"this": True, "expression": True, "unit": False}
3505
3506
3507class TimeDiff(Func, TimeUnit):
3508    arg_types = {"this": True, "expression": True, "unit": False}
3509
3510
3511class TimeTrunc(Func, TimeUnit):
3512    arg_types = {"this": True, "unit": True, "zone": False}
3513
3514
3515class DateFromParts(Func):
3516    _sql_names = ["DATEFROMPARTS"]
3517    arg_types = {"year": True, "month": True, "day": True}
3518
3519
3520class DateStrToDate(Func):
3521    pass
3522
3523
3524class DateToDateStr(Func):
3525    pass
3526
3527
3528class DateToDi(Func):
3529    pass
3530
3531
3532class Day(Func):
3533    pass
3534
3535
3536class Decode(Func):
3537    arg_types = {"this": True, "charset": True, "replace": False}
3538
3539
3540class DiToDate(Func):
3541    pass
3542
3543
3544class Encode(Func):
3545    arg_types = {"this": True, "charset": True}
3546
3547
3548class Exp(Func):
3549    pass
3550
3551
3552class Explode(Func):
3553    pass
3554
3555
3556class ExponentialTimeDecayedAvg(AggFunc):
3557    arg_types = {"this": True, "time": False, "decay": False}
3558
3559
3560class Floor(Func):
3561    arg_types = {"this": True, "decimals": False}
3562
3563
3564class Greatest(Func):
3565    arg_types = {"this": True, "expressions": False}
3566    is_var_len_args = True
3567
3568
3569class GroupConcat(Func):
3570    arg_types = {"this": True, "separator": False}
3571
3572
3573class GroupUniqArray(AggFunc):
3574    arg_types = {"this": True, "size": False}
3575
3576
3577class Hex(Func):
3578    pass
3579
3580
3581class Histogram(AggFunc):
3582    arg_types = {"this": True, "bins": False}
3583
3584
3585class If(Func):
3586    arg_types = {"this": True, "true": True, "false": False}
3587
3588
3589class IfNull(Func):
3590    arg_types = {"this": True, "expression": False}
3591    _sql_names = ["IFNULL", "NVL"]
3592
3593
3594class Initcap(Func):
3595    pass
3596
3597
3598class JSONBContains(Binary):
3599    _sql_names = ["JSONB_CONTAINS"]
3600
3601
3602class JSONExtract(Binary, Func):
3603    _sql_names = ["JSON_EXTRACT"]
3604
3605
3606class JSONExtractScalar(JSONExtract):
3607    _sql_names = ["JSON_EXTRACT_SCALAR"]
3608
3609
3610class JSONBExtract(JSONExtract):
3611    _sql_names = ["JSONB_EXTRACT"]
3612
3613
3614class JSONBExtractScalar(JSONExtract):
3615    _sql_names = ["JSONB_EXTRACT_SCALAR"]
3616
3617
3618class Least(Func):
3619    arg_types = {"expressions": False}
3620    is_var_len_args = True
3621
3622
3623class Length(Func):
3624    pass
3625
3626
3627class Levenshtein(Func):
3628    arg_types = {
3629        "this": True,
3630        "expression": False,
3631        "ins_cost": False,
3632        "del_cost": False,
3633        "sub_cost": False,
3634    }
3635
3636
3637class Ln(Func):
3638    pass
3639
3640
3641class Log(Func):
3642    arg_types = {"this": True, "expression": False}
3643
3644
3645class Log2(Func):
3646    pass
3647
3648
3649class Log10(Func):
3650    pass
3651
3652
3653class LogicalOr(AggFunc):
3654    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
3655
3656
3657class LogicalAnd(AggFunc):
3658    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
3659
3660
3661class Lower(Func):
3662    _sql_names = ["LOWER", "LCASE"]
3663
3664
3665class Map(Func):
3666    arg_types = {"keys": False, "values": False}
3667
3668
3669class VarMap(Func):
3670    arg_types = {"keys": True, "values": True}
3671    is_var_len_args = True
3672
3673
3674class Matches(Func):
3675    """Oracle/Snowflake decode.
3676    https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions040.htm
3677    Pattern matching MATCHES(value, search1, result1, ...searchN, resultN, else)
3678    """
3679
3680    arg_types = {"this": True, "expressions": True}
3681    is_var_len_args = True
3682
3683
3684class Max(AggFunc):
3685    arg_types = {"this": True, "expressions": False}
3686    is_var_len_args = True
3687
3688
3689class Min(AggFunc):
3690    arg_types = {"this": True, "expressions": False}
3691    is_var_len_args = True
3692
3693
3694class Month(Func):
3695    pass
3696
3697
3698class Nvl2(Func):
3699    arg_types = {"this": True, "true": True, "false": False}
3700
3701
3702class Posexplode(Func):
3703    pass
3704
3705
3706class Pow(Binary, Func):
3707    _sql_names = ["POWER", "POW"]
3708
3709
3710class PercentileCont(AggFunc):
3711    pass
3712
3713
3714class PercentileDisc(AggFunc):
3715    pass
3716
3717
3718class Quantile(AggFunc):
3719    arg_types = {"this": True, "quantile": True}
3720
3721
3722# Clickhouse-specific:
3723# https://clickhouse.com/docs/en/sql-reference/aggregate-functions/reference/quantiles/#quantiles
3724class Quantiles(AggFunc):
3725    arg_types = {"parameters": True, "expressions": True}
3726    is_var_len_args = True
3727
3728
3729class QuantileIf(AggFunc):
3730    arg_types = {"parameters": True, "expressions": True}
3731
3732
3733class ApproxQuantile(Quantile):
3734    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
3735
3736
3737class RangeN(Func):
3738    arg_types = {"this": True, "expressions": True, "each": False}
3739
3740
3741class ReadCSV(Func):
3742    _sql_names = ["READ_CSV"]
3743    is_var_len_args = True
3744    arg_types = {"this": True, "expressions": False}
3745
3746
3747class Reduce(Func):
3748    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
3749
3750
3751class RegexpExtract(Func):
3752    arg_types = {
3753        "this": True,
3754        "expression": True,
3755        "position": False,
3756        "occurrence": False,
3757        "group": False,
3758    }
3759
3760
3761class RegexpLike(Func):
3762    arg_types = {"this": True, "expression": True, "flag": False}
3763
3764
3765class RegexpILike(Func):
3766    arg_types = {"this": True, "expression": True, "flag": False}
3767
3768
3769class RegexpSplit(Func):
3770    arg_types = {"this": True, "expression": True}
3771
3772
3773class Repeat(Func):
3774    arg_types = {"this": True, "times": True}
3775
3776
3777class Round(Func):
3778    arg_types = {"this": True, "decimals": False}
3779
3780
3781class RowNumber(Func):
3782    arg_types: t.Dict[str, t.Any] = {}
3783
3784
3785class SafeDivide(Func):
3786    arg_types = {"this": True, "expression": True}
3787
3788
3789class SetAgg(AggFunc):
3790    pass
3791
3792
3793class SortArray(Func):
3794    arg_types = {"this": True, "asc": False}
3795
3796
3797class Split(Func):
3798    arg_types = {"this": True, "expression": True, "limit": False}
3799
3800
3801# Start may be omitted in the case of postgres
3802# https://www.postgresql.org/docs/9.1/functions-string.html @ Table 9-6
3803class Substring(Func):
3804    arg_types = {"this": True, "start": False, "length": False}
3805
3806
3807class StrPosition(Func):
3808    arg_types = {
3809        "this": True,
3810        "substr": True,
3811        "position": False,
3812        "instance": False,
3813    }
3814
3815
3816class StrToDate(Func):
3817    arg_types = {"this": True, "format": True}
3818
3819
3820class StrToTime(Func):
3821    arg_types = {"this": True, "format": True}
3822
3823
3824# Spark allows unix_timestamp()
3825# https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.functions.unix_timestamp.html
3826class StrToUnix(Func):
3827    arg_types = {"this": False, "format": False}
3828
3829
3830class NumberToStr(Func):
3831    arg_types = {"this": True, "format": True}
3832
3833
3834class Struct(Func):
3835    arg_types = {"expressions": True}
3836    is_var_len_args = True
3837
3838
3839class StructExtract(Func):
3840    arg_types = {"this": True, "expression": True}
3841
3842
3843class Sum(AggFunc):
3844    pass
3845
3846
3847class Sqrt(Func):
3848    pass
3849
3850
3851class Stddev(AggFunc):
3852    pass
3853
3854
3855class StddevPop(AggFunc):
3856    pass
3857
3858
3859class StddevSamp(AggFunc):
3860    pass
3861
3862
3863class TimeToStr(Func):
3864    arg_types = {"this": True, "format": True}
3865
3866
3867class TimeToTimeStr(Func):
3868    pass
3869
3870
3871class TimeToUnix(Func):
3872    pass
3873
3874
3875class TimeStrToDate(Func):
3876    pass
3877
3878
3879class TimeStrToTime(Func):
3880    pass
3881
3882
3883class TimeStrToUnix(Func):
3884    pass
3885
3886
3887class Trim(Func):
3888    arg_types = {
3889        "this": True,
3890        "expression": False,
3891        "position": False,
3892        "collation": False,
3893    }
3894
3895
3896class TsOrDsAdd(Func, TimeUnit):
3897    arg_types = {"this": True, "expression": True, "unit": False}
3898
3899
3900class TsOrDsToDateStr(Func):
3901    pass
3902
3903
3904class TsOrDsToDate(Func):
3905    arg_types = {"this": True, "format": False}
3906
3907
3908class TsOrDiToDi(Func):
3909    pass
3910
3911
3912class Unhex(Func):
3913    pass
3914
3915
3916class UnixToStr(Func):
3917    arg_types = {"this": True, "format": False}
3918
3919
3920# https://prestodb.io/docs/current/functions/datetime.html
3921# presto has weird zone/hours/minutes
3922class UnixToTime(Func):
3923    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
3924
3925    SECONDS = Literal.string("seconds")
3926    MILLIS = Literal.string("millis")
3927    MICROS = Literal.string("micros")
3928
3929
3930class UnixToTimeStr(Func):
3931    pass
3932
3933
3934class Upper(Func):
3935    _sql_names = ["UPPER", "UCASE"]
3936
3937
3938class Variance(AggFunc):
3939    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
3940
3941
3942class VariancePop(AggFunc):
3943    _sql_names = ["VARIANCE_POP", "VAR_POP"]
3944
3945
3946class Week(Func):
3947    arg_types = {"this": True, "mode": False}
3948
3949
3950class XMLTable(Func):
3951    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
3952
3953
3954class Year(Func):
3955    pass
3956
3957
3958class Use(Expression):
3959    arg_types = {"this": True, "kind": False}
3960
3961
3962class Merge(Expression):
3963    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
3964
3965
3966class When(Func):
3967    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
3968
3969
3970def _norm_args(expression):
3971    args = {}
3972
3973    for k, arg in expression.args.items():
3974        if isinstance(arg, list):
3975            arg = [_norm_arg(a) for a in arg]
3976            if not arg:
3977                arg = None
3978        else:
3979            arg = _norm_arg(arg)
3980
3981        if arg is not None and arg is not False:
3982            args[k] = arg
3983
3984    return args
3985
3986
3987def _norm_arg(arg):
3988    return arg.lower() if isinstance(arg, str) else arg
3989
3990
3991ALL_FUNCTIONS = subclasses(__name__, Func, (AggFunc, Anonymous, Func))
3992
3993
3994# Helpers
3995def maybe_parse(
3996    sql_or_expression: ExpOrStr,
3997    *,
3998    into: t.Optional[IntoType] = None,
3999    dialect: DialectType = None,
4000    prefix: t.Optional[str] = None,
4001    copy: bool = False,
4002    **opts,
4003) -> Expression:
4004    """Gracefully handle a possible string or expression.
4005
4006    Example:
4007        >>> maybe_parse("1")
4008        (LITERAL this: 1, is_string: False)
4009        >>> maybe_parse(to_identifier("x"))
4010        (IDENTIFIER this: x, quoted: False)
4011
4012    Args:
4013        sql_or_expression: the SQL code string or an expression
4014        into: the SQLGlot Expression to parse into
4015        dialect: the dialect used to parse the input expressions (in the case that an
4016            input expression is a SQL string).
4017        prefix: a string to prefix the sql with before it gets parsed
4018            (automatically includes a space)
4019        copy: whether or not to copy the expression.
4020        **opts: other options to use to parse the input expressions (again, in the case
4021            that an input expression is a SQL string).
4022
4023    Returns:
4024        Expression: the parsed or given expression.
4025    """
4026    if isinstance(sql_or_expression, Expression):
4027        if copy:
4028            return sql_or_expression.copy()
4029        return sql_or_expression
4030
4031    import sqlglot
4032
4033    sql = str(sql_or_expression)
4034    if prefix:
4035        sql = f"{prefix} {sql}"
4036    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)
4037
4038
4039def _maybe_copy(instance, copy=True):
4040    return instance.copy() if copy else instance
4041
4042
4043def _is_wrong_expression(expression, into):
4044    return isinstance(expression, Expression) and not isinstance(expression, into)
4045
4046
4047def _apply_builder(
4048    expression,
4049    instance,
4050    arg,
4051    copy=True,
4052    prefix=None,
4053    into=None,
4054    dialect=None,
4055    **opts,
4056):
4057    if _is_wrong_expression(expression, into):
4058        expression = into(this=expression)
4059    instance = _maybe_copy(instance, copy)
4060    expression = maybe_parse(
4061        sql_or_expression=expression,
4062        prefix=prefix,
4063        into=into,
4064        dialect=dialect,
4065        **opts,
4066    )
4067    instance.set(arg, expression)
4068    return instance
4069
4070
4071def _apply_child_list_builder(
4072    *expressions,
4073    instance,
4074    arg,
4075    append=True,
4076    copy=True,
4077    prefix=None,
4078    into=None,
4079    dialect=None,
4080    properties=None,
4081    **opts,
4082):
4083    instance = _maybe_copy(instance, copy)
4084    parsed = []
4085    for expression in expressions:
4086        if _is_wrong_expression(expression, into):
4087            expression = into(expressions=[expression])
4088        expression = maybe_parse(
4089            expression,
4090            into=into,
4091            dialect=dialect,
4092            prefix=prefix,
4093            **opts,
4094        )
4095        parsed.extend(expression.expressions)
4096
4097    existing = instance.args.get(arg)
4098    if append and existing:
4099        parsed = existing.expressions + parsed
4100
4101    child = into(expressions=parsed)
4102    for k, v in (properties or {}).items():
4103        child.set(k, v)
4104    instance.set(arg, child)
4105    return instance
4106
4107
4108def _apply_list_builder(
4109    *expressions,
4110    instance,
4111    arg,
4112    append=True,
4113    copy=True,
4114    prefix=None,
4115    into=None,
4116    dialect=None,
4117    **opts,
4118):
4119    inst = _maybe_copy(instance, copy)
4120
4121    expressions = [
4122        maybe_parse(
4123            sql_or_expression=expression,
4124            into=into,
4125            prefix=prefix,
4126            dialect=dialect,
4127            **opts,
4128        )
4129        for expression in expressions
4130    ]
4131
4132    existing_expressions = inst.args.get(arg)
4133    if append and existing_expressions:
4134        expressions = existing_expressions + expressions
4135
4136    inst.set(arg, expressions)
4137    return inst
4138
4139
4140def _apply_conjunction_builder(
4141    *expressions,
4142    instance,
4143    arg,
4144    into=None,
4145    append=True,
4146    copy=True,
4147    dialect=None,
4148    **opts,
4149):
4150    expressions = [exp for exp in expressions if exp is not None and exp != ""]
4151    if not expressions:
4152        return instance
4153
4154    inst = _maybe_copy(instance, copy)
4155
4156    existing = inst.args.get(arg)
4157    if append and existing is not None:
4158        expressions = [existing.this if into else existing] + list(expressions)
4159
4160    node = and_(*expressions, dialect=dialect, **opts)
4161
4162    inst.set(arg, into(this=node) if into else node)
4163    return inst
4164
4165
4166def _combine(expressions, operator, dialect=None, **opts):
4167    expressions = [condition(expression, dialect=dialect, **opts) for expression in expressions]
4168    this = expressions[0]
4169    if expressions[1:]:
4170        this = _wrap_operator(this)
4171    for expression in expressions[1:]:
4172        this = operator(this=this, expression=_wrap_operator(expression))
4173    return this
4174
4175
4176def _wrap_operator(expression):
4177    if isinstance(expression, (And, Or, Not)):
4178        expression = Paren(this=expression)
4179    return expression
4180
4181
4182def union(left, right, distinct=True, dialect=None, **opts):
4183    """
4184    Initializes a syntax tree from one UNION expression.
4185
4186    Example:
4187        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4188        'SELECT * FROM foo UNION SELECT * FROM bla'
4189
4190    Args:
4191        left (str | Expression): the SQL code string corresponding to the left-hand side.
4192            If an `Expression` instance is passed, it will be used as-is.
4193        right (str | Expression): the SQL code string corresponding to the right-hand side.
4194            If an `Expression` instance is passed, it will be used as-is.
4195        distinct (bool): set the DISTINCT flag if and only if this is true.
4196        dialect (str): the dialect used to parse the input expression.
4197        opts (kwargs): other options to use to parse the input expressions.
4198    Returns:
4199        Union: the syntax tree for the UNION expression.
4200    """
4201    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4202    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4203
4204    return Union(this=left, expression=right, distinct=distinct)
4205
4206
4207def intersect(left, right, distinct=True, dialect=None, **opts):
4208    """
4209    Initializes a syntax tree from one INTERSECT expression.
4210
4211    Example:
4212        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4213        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4214
4215    Args:
4216        left (str | Expression): the SQL code string corresponding to the left-hand side.
4217            If an `Expression` instance is passed, it will be used as-is.
4218        right (str | Expression): the SQL code string corresponding to the right-hand side.
4219            If an `Expression` instance is passed, it will be used as-is.
4220        distinct (bool): set the DISTINCT flag if and only if this is true.
4221        dialect (str): the dialect used to parse the input expression.
4222        opts (kwargs): other options to use to parse the input expressions.
4223    Returns:
4224        Intersect: the syntax tree for the INTERSECT expression.
4225    """
4226    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4227    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4228
4229    return Intersect(this=left, expression=right, distinct=distinct)
4230
4231
4232def except_(left, right, distinct=True, dialect=None, **opts):
4233    """
4234    Initializes a syntax tree from one EXCEPT expression.
4235
4236    Example:
4237        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4238        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4239
4240    Args:
4241        left (str | Expression): the SQL code string corresponding to the left-hand side.
4242            If an `Expression` instance is passed, it will be used as-is.
4243        right (str | Expression): the SQL code string corresponding to the right-hand side.
4244            If an `Expression` instance is passed, it will be used as-is.
4245        distinct (bool): set the DISTINCT flag if and only if this is true.
4246        dialect (str): the dialect used to parse the input expression.
4247        opts (kwargs): other options to use to parse the input expressions.
4248    Returns:
4249        Except: the syntax tree for the EXCEPT statement.
4250    """
4251    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4252    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4253
4254    return Except(this=left, expression=right, distinct=distinct)
4255
4256
4257def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4258    """
4259    Initializes a syntax tree from one or multiple SELECT expressions.
4260
4261    Example:
4262        >>> select("col1", "col2").from_("tbl").sql()
4263        'SELECT col1, col2 FROM tbl'
4264
4265    Args:
4266        *expressions: the SQL code string to parse as the expressions of a
4267            SELECT statement. If an Expression instance is passed, this is used as-is.
4268        dialect: the dialect used to parse the input expressions (in the case that an
4269            input expression is a SQL string).
4270        **opts: other options to use to parse the input expressions (again, in the case
4271            that an input expression is a SQL string).
4272
4273    Returns:
4274        Select: the syntax tree for the SELECT statement.
4275    """
4276    return Select().select(*expressions, dialect=dialect, **opts)
4277
4278
4279def from_(*expressions, dialect=None, **opts) -> Select:
4280    """
4281    Initializes a syntax tree from a FROM expression.
4282
4283    Example:
4284        >>> from_("tbl").select("col1", "col2").sql()
4285        'SELECT col1, col2 FROM tbl'
4286
4287    Args:
4288        *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a
4289            SELECT statement. If an Expression instance is passed, this is used as-is.
4290        dialect (str): the dialect used to parse the input expression (in the case that the
4291            input expression is a SQL string).
4292        **opts: other options to use to parse the input expressions (again, in the case
4293            that the input expression is a SQL string).
4294
4295    Returns:
4296        Select: the syntax tree for the SELECT statement.
4297    """
4298    return Select().from_(*expressions, dialect=dialect, **opts)
4299
4300
4301def update(
4302    table: str | Table,
4303    properties: dict,
4304    where: t.Optional[ExpOrStr] = None,
4305    from_: t.Optional[ExpOrStr] = None,
4306    dialect: DialectType = None,
4307    **opts,
4308) -> Update:
4309    """
4310    Creates an update statement.
4311
4312    Example:
4313        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
4314        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
4315
4316    Args:
4317        *properties: dictionary of properties to set which are
4318            auto converted to sql objects eg None -> NULL
4319        where: sql conditional parsed into a WHERE statement
4320        from_: sql statement parsed into a FROM statement
4321        dialect: the dialect used to parse the input expressions.
4322        **opts: other options to use to parse the input expressions.
4323
4324    Returns:
4325        Update: the syntax tree for the UPDATE statement.
4326    """
4327    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
4328    update_expr.set(
4329        "expressions",
4330        [
4331            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
4332            for k, v in properties.items()
4333        ],
4334    )
4335    if from_:
4336        update_expr.set(
4337            "from",
4338            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
4339        )
4340    if isinstance(where, Condition):
4341        where = Where(this=where)
4342    if where:
4343        update_expr.set(
4344            "where",
4345            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
4346        )
4347    return update_expr
4348
4349
4350def delete(
4351    table: ExpOrStr,
4352    where: t.Optional[ExpOrStr] = None,
4353    returning: t.Optional[ExpOrStr] = None,
4354    dialect: DialectType = None,
4355    **opts,
4356) -> Delete:
4357    """
4358    Builds a delete statement.
4359
4360    Example:
4361        >>> delete("my_table", where="id > 1").sql()
4362        'DELETE FROM my_table WHERE id > 1'
4363
4364    Args:
4365        where: sql conditional parsed into a WHERE statement
4366        returning: sql conditional parsed into a RETURNING statement
4367        dialect: the dialect used to parse the input expressions.
4368        **opts: other options to use to parse the input expressions.
4369
4370    Returns:
4371        Delete: the syntax tree for the DELETE statement.
4372    """
4373    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
4374    if where:
4375        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
4376    if returning:
4377        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
4378    return delete_expr
4379
4380
4381def condition(expression, dialect=None, **opts) -> Condition:
4382    """
4383    Initialize a logical condition expression.
4384
4385    Example:
4386        >>> condition("x=1").sql()
4387        'x = 1'
4388
4389        This is helpful for composing larger logical syntax trees:
4390        >>> where = condition("x=1")
4391        >>> where = where.and_("y=1")
4392        >>> Select().from_("tbl").select("*").where(where).sql()
4393        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
4394
4395    Args:
4396        *expression (str | Expression): the SQL code string to parse.
4397            If an Expression instance is passed, this is used as-is.
4398        dialect (str): the dialect used to parse the input expression (in the case that the
4399            input expression is a SQL string).
4400        **opts: other options to use to parse the input expressions (again, in the case
4401            that the input expression is a SQL string).
4402
4403    Returns:
4404        Condition: the expression
4405    """
4406    return maybe_parse(  # type: ignore
4407        expression,
4408        into=Condition,
4409        dialect=dialect,
4410        **opts,
4411    )
4412
4413
4414def and_(*expressions, dialect=None, **opts) -> And:
4415    """
4416    Combine multiple conditions with an AND logical operator.
4417
4418    Example:
4419        >>> and_("x=1", and_("y=1", "z=1")).sql()
4420        'x = 1 AND (y = 1 AND z = 1)'
4421
4422    Args:
4423        *expressions (str | Expression): the SQL code strings to parse.
4424            If an Expression instance is passed, this is used as-is.
4425        dialect (str): the dialect used to parse the input expression.
4426        **opts: other options to use to parse the input expressions.
4427
4428    Returns:
4429        And: the new condition
4430    """
4431    return _combine(expressions, And, dialect, **opts)
4432
4433
4434def or_(*expressions, dialect=None, **opts) -> Or:
4435    """
4436    Combine multiple conditions with an OR logical operator.
4437
4438    Example:
4439        >>> or_("x=1", or_("y=1", "z=1")).sql()
4440        'x = 1 OR (y = 1 OR z = 1)'
4441
4442    Args:
4443        *expressions (str | Expression): the SQL code strings to parse.
4444            If an Expression instance is passed, this is used as-is.
4445        dialect (str): the dialect used to parse the input expression.
4446        **opts: other options to use to parse the input expressions.
4447
4448    Returns:
4449        Or: the new condition
4450    """
4451    return _combine(expressions, Or, dialect, **opts)
4452
4453
4454def not_(expression, dialect=None, **opts) -> Not:
4455    """
4456    Wrap a condition with a NOT operator.
4457
4458    Example:
4459        >>> not_("this_suit='black'").sql()
4460        "NOT this_suit = 'black'"
4461
4462    Args:
4463        expression (str | Expression): the SQL code strings to parse.
4464            If an Expression instance is passed, this is used as-is.
4465        dialect (str): the dialect used to parse the input expression.
4466        **opts: other options to use to parse the input expressions.
4467
4468    Returns:
4469        Not: the new condition
4470    """
4471    this = condition(
4472        expression,
4473        dialect=dialect,
4474        **opts,
4475    )
4476    return Not(this=_wrap_operator(this))
4477
4478
4479def paren(expression) -> Paren:
4480    return Paren(this=expression)
4481
4482
4483SAFE_IDENTIFIER_RE = re.compile(r"^[_a-zA-Z][\w]*$")
4484
4485
4486@t.overload
4487def to_identifier(name: None, quoted: t.Optional[bool] = None) -> None:
4488    ...
4489
4490
4491@t.overload
4492def to_identifier(name: str | Identifier, quoted: t.Optional[bool] = None) -> Identifier:
4493    ...
4494
4495
4496def to_identifier(name, quoted=None):
4497    """Builds an identifier.
4498
4499    Args:
4500        name: The name to turn into an identifier.
4501        quoted: Whether or not force quote the identifier.
4502
4503    Returns:
4504        The identifier ast node.
4505    """
4506
4507    if name is None:
4508        return None
4509
4510    if isinstance(name, Identifier):
4511        identifier = name
4512    elif isinstance(name, str):
4513        identifier = Identifier(
4514            this=name,
4515            quoted=not re.match(SAFE_IDENTIFIER_RE, name) if quoted is None else quoted,
4516        )
4517    else:
4518        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
4519    return identifier
4520
4521
4522INTERVAL_STRING_RE = re.compile(r"\s*([0-9]+)\s*([a-zA-Z]+)\s*")
4523
4524
4525def to_interval(interval: str | Literal) -> Interval:
4526    """Builds an interval expression from a string like '1 day' or '5 months'."""
4527    if isinstance(interval, Literal):
4528        if not interval.is_string:
4529            raise ValueError("Invalid interval string.")
4530
4531        interval = interval.this
4532
4533    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
4534
4535    if not interval_parts:
4536        raise ValueError("Invalid interval string.")
4537
4538    return Interval(
4539        this=Literal.string(interval_parts.group(1)),
4540        unit=Var(this=interval_parts.group(2)),
4541    )
4542
4543
4544@t.overload
4545def to_table(sql_path: str | Table, **kwargs) -> Table:
4546    ...
4547
4548
4549@t.overload
4550def to_table(sql_path: None, **kwargs) -> None:
4551    ...
4552
4553
4554def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]:
4555    """
4556    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
4557    If a table is passed in then that table is returned.
4558
4559    Args:
4560        sql_path: a `[catalog].[schema].[table]` string.
4561
4562    Returns:
4563        A table expression.
4564    """
4565    if sql_path is None or isinstance(sql_path, Table):
4566        return sql_path
4567    if not isinstance(sql_path, str):
4568        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
4569
4570    catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3))
4571    return Table(this=table_name, db=db, catalog=catalog, **kwargs)
4572
4573
4574def to_column(sql_path: str | Column, **kwargs) -> Column:
4575    """
4576    Create a column from a `[table].[column]` sql path. Schema is optional.
4577
4578    If a column is passed in then that column is returned.
4579
4580    Args:
4581        sql_path: `[table].[column]` string
4582    Returns:
4583        Table: A column expression
4584    """
4585    if sql_path is None or isinstance(sql_path, Column):
4586        return sql_path
4587    if not isinstance(sql_path, str):
4588        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
4589    table_name, column_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 2))
4590    return Column(this=column_name, table=table_name, **kwargs)
4591
4592
4593def alias_(
4594    expression: ExpOrStr,
4595    alias: str | Identifier,
4596    table: bool | t.Sequence[str | Identifier] = False,
4597    quoted: t.Optional[bool] = None,
4598    dialect: DialectType = None,
4599    **opts,
4600):
4601    """Create an Alias expression.
4602
4603    Example:
4604        >>> alias_('foo', 'bar').sql()
4605        'foo AS bar'
4606
4607        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
4608        '(SELECT 1, 2) AS bar(a, b)'
4609
4610    Args:
4611        expression: the SQL code strings to parse.
4612            If an Expression instance is passed, this is used as-is.
4613        alias: the alias name to use. If the name has
4614            special characters it is quoted.
4615        table: Whether or not to create a table alias, can also be a list of columns.
4616        quoted: whether or not to quote the alias
4617        dialect: the dialect used to parse the input expression.
4618        **opts: other options to use to parse the input expressions.
4619
4620    Returns:
4621        Alias: the aliased expression
4622    """
4623    exp = maybe_parse(expression, dialect=dialect, **opts)
4624    alias = to_identifier(alias, quoted=quoted)
4625
4626    if table:
4627        table_alias = TableAlias(this=alias)
4628        exp.set("alias", table_alias)
4629
4630        if not isinstance(table, bool):
4631            for column in table:
4632                table_alias.append("columns", to_identifier(column, quoted=quoted))
4633
4634        return exp
4635
4636    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
4637    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
4638    # for the complete Window expression.
4639    #
4640    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
4641
4642    if "alias" in exp.arg_types and not isinstance(exp, Window):
4643        exp = exp.copy()
4644        exp.set("alias", alias)
4645        return exp
4646    return Alias(this=exp, alias=alias)
4647
4648
4649def subquery(expression, alias=None, dialect=None, **opts):
4650    """
4651    Build a subquery expression.
4652
4653    Example:
4654        >>> subquery('select x from tbl', 'bar').select('x').sql()
4655        'SELECT x FROM (SELECT x FROM tbl) AS bar'
4656
4657    Args:
4658        expression (str | Expression): the SQL code strings to parse.
4659            If an Expression instance is passed, this is used as-is.
4660        alias (str | Expression): the alias name to use.
4661        dialect (str): the dialect used to parse the input expression.
4662        **opts: other options to use to parse the input expressions.
4663
4664    Returns:
4665        Select: a new select with the subquery expression included
4666    """
4667
4668    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
4669    return Select().from_(expression, dialect=dialect, **opts)
4670
4671
4672def column(
4673    col: str | Identifier,
4674    table: t.Optional[str | Identifier] = None,
4675    schema: t.Optional[str | Identifier] = None,
4676    quoted: t.Optional[bool] = None,
4677) -> Column:
4678    """
4679    Build a Column.
4680
4681    Args:
4682        col: column name
4683        table: table name
4684        schema: schema name
4685        quoted: whether or not to force quote each part
4686    Returns:
4687        Column: column instance
4688    """
4689    return Column(
4690        this=to_identifier(col, quoted=quoted),
4691        table=to_identifier(table, quoted=quoted),
4692        schema=to_identifier(schema, quoted=quoted),
4693    )
4694
4695
4696def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
4697    """Cast an expression to a data type.
4698
4699    Example:
4700        >>> cast('x + 1', 'int').sql()
4701        'CAST(x + 1 AS INT)'
4702
4703    Args:
4704        expression: The expression to cast.
4705        to: The datatype to cast to.
4706
4707    Returns:
4708        A cast node.
4709    """
4710    expression = maybe_parse(expression, **opts)
4711    return Cast(this=expression, to=DataType.build(to, **opts))
4712
4713
4714def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table:
4715    """Build a Table.
4716
4717    Args:
4718        table (str | Expression): column name
4719        db (str | Expression): db name
4720        catalog (str | Expression): catalog name
4721
4722    Returns:
4723        Table: table instance
4724    """
4725    return Table(
4726        this=to_identifier(table, quoted=quoted),
4727        db=to_identifier(db, quoted=quoted),
4728        catalog=to_identifier(catalog, quoted=quoted),
4729        alias=TableAlias(this=to_identifier(alias)) if alias else None,
4730    )
4731
4732
4733def values(
4734    values: t.Iterable[t.Tuple[t.Any, ...]],
4735    alias: t.Optional[str] = None,
4736    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
4737) -> Values:
4738    """Build VALUES statement.
4739
4740    Example:
4741        >>> values([(1, '2')]).sql()
4742        "VALUES (1, '2')"
4743
4744    Args:
4745        values: values statements that will be converted to SQL
4746        alias: optional alias
4747        columns: Optional list of ordered column names or ordered dictionary of column names to types.
4748         If either are provided then an alias is also required.
4749         If a dictionary is provided then the first column of the values will be casted to the expected type
4750         in order to help with type inference.
4751
4752    Returns:
4753        Values: the Values expression object
4754    """
4755    if columns and not alias:
4756        raise ValueError("Alias is required when providing columns")
4757    table_alias = (
4758        TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
4759        if columns
4760        else TableAlias(this=to_identifier(alias) if alias else None)
4761    )
4762    expressions = [convert(tup) for tup in values]
4763    if columns and isinstance(columns, dict):
4764        types = list(columns.values())
4765        expressions[0].set(
4766            "expressions",
4767            [cast(x, types[i]) for i, x in enumerate(expressions[0].expressions)],
4768        )
4769    return Values(
4770        expressions=expressions,
4771        alias=table_alias,
4772    )
4773
4774
4775def var(name: t.Optional[ExpOrStr]) -> Var:
4776    """Build a SQL variable.
4777
4778    Example:
4779        >>> repr(var('x'))
4780        '(VAR this: x)'
4781
4782        >>> repr(var(column('x', table='y')))
4783        '(VAR this: x)'
4784
4785    Args:
4786        name: The name of the var or an expression who's name will become the var.
4787
4788    Returns:
4789        The new variable node.
4790    """
4791    if not name:
4792        raise ValueError("Cannot convert empty name into var.")
4793
4794    if isinstance(name, Expression):
4795        name = name.name
4796    return Var(this=name)
4797
4798
4799def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
4800    """Build ALTER TABLE... RENAME... expression
4801
4802    Args:
4803        old_name: The old name of the table
4804        new_name: The new name of the table
4805
4806    Returns:
4807        Alter table expression
4808    """
4809    old_table = to_table(old_name)
4810    new_table = to_table(new_name)
4811    return AlterTable(
4812        this=old_table,
4813        actions=[
4814            RenameTable(this=new_table),
4815        ],
4816    )
4817
4818
4819def convert(value) -> Expression:
4820    """Convert a python value into an expression object.
4821
4822    Raises an error if a conversion is not possible.
4823
4824    Args:
4825        value (Any): a python object
4826
4827    Returns:
4828        Expression: the equivalent expression object
4829    """
4830    if isinstance(value, Expression):
4831        return value
4832    if value is None:
4833        return NULL
4834    if isinstance(value, bool):
4835        return Boolean(this=value)
4836    if isinstance(value, str):
4837        return Literal.string(value)
4838    if isinstance(value, float) and math.isnan(value):
4839        return NULL
4840    if isinstance(value, numbers.Number):
4841        return Literal.number(value)
4842    if isinstance(value, tuple):
4843        return Tuple(expressions=[convert(v) for v in value])
4844    if isinstance(value, list):
4845        return Array(expressions=[convert(v) for v in value])
4846    if isinstance(value, dict):
4847        return Map(
4848            keys=[convert(k) for k in value],
4849            values=[convert(v) for v in value.values()],
4850        )
4851    if isinstance(value, datetime.datetime):
4852        datetime_literal = Literal.string(
4853            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
4854        )
4855        return TimeStrToTime(this=datetime_literal)
4856    if isinstance(value, datetime.date):
4857        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
4858        return DateStrToDate(this=date_literal)
4859    raise ValueError(f"Cannot convert {value}")
4860
4861
4862def replace_children(expression, fun, *args, **kwargs):
4863    """
4864    Replace children of an expression with the result of a lambda fun(child) -> exp.
4865    """
4866    for k, v in expression.args.items():
4867        is_list_arg = isinstance(v, list)
4868
4869        child_nodes = v if is_list_arg else [v]
4870        new_child_nodes = []
4871
4872        for cn in child_nodes:
4873            if isinstance(cn, Expression):
4874                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
4875                    new_child_nodes.append(child_node)
4876                    child_node.parent = expression
4877                    child_node.arg_key = k
4878            else:
4879                new_child_nodes.append(cn)
4880
4881        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)
4882
4883
4884def column_table_names(expression):
4885    """
4886    Return all table names referenced through columns in an expression.
4887
4888    Example:
4889        >>> import sqlglot
4890        >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
4891        ['c', 'a']
4892
4893    Args:
4894        expression (sqlglot.Expression): expression to find table names
4895
4896    Returns:
4897        list: A list of unique names
4898    """
4899    return list(dict.fromkeys(column.table for column in expression.find_all(Column)))
4900
4901
4902def table_name(table) -> str:
4903    """Get the full name of a table as a string.
4904
4905    Args:
4906        table (exp.Table | str): table expression node or string.
4907
4908    Examples:
4909        >>> from sqlglot import exp, parse_one
4910        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
4911        'a.b.c'
4912
4913    Returns:
4914        The table name.
4915    """
4916
4917    table = maybe_parse(table, into=Table)
4918
4919    if not table:
4920        raise ValueError(f"Cannot parse {table}")
4921
4922    return ".".join(
4923        part
4924        for part in (
4925            table.text("catalog"),
4926            table.text("db"),
4927            table.name,
4928        )
4929        if part
4930    )
4931
4932
4933def replace_tables(expression, mapping):
4934    """Replace all tables in expression according to the mapping.
4935
4936    Args:
4937        expression (sqlglot.Expression): expression node to be transformed and replaced.
4938        mapping (Dict[str, str]): mapping of table names.
4939
4940    Examples:
4941        >>> from sqlglot import exp, parse_one
4942        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
4943        'SELECT * FROM c'
4944
4945    Returns:
4946        The mapped expression.
4947    """
4948
4949    def _replace_tables(node):
4950        if isinstance(node, Table):
4951            new_name = mapping.get(table_name(node))
4952            if new_name:
4953                return to_table(
4954                    new_name,
4955                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
4956                )
4957        return node
4958
4959    return expression.transform(_replace_tables)
4960
4961
4962def replace_placeholders(expression, *args, **kwargs):
4963    """Replace placeholders in an expression.
4964
4965    Args:
4966        expression (sqlglot.Expression): expression node to be transformed and replaced.
4967        args: positional names that will substitute unnamed placeholders in the given order.
4968        kwargs: keyword arguments that will substitute named placeholders.
4969
4970    Examples:
4971        >>> from sqlglot import exp, parse_one
4972        >>> replace_placeholders(
4973        ...     parse_one("select * from :tbl where ? = ?"), "a", "b", tbl="foo"
4974        ... ).sql()
4975        'SELECT * FROM foo WHERE a = b'
4976
4977    Returns:
4978        The mapped expression.
4979    """
4980
4981    def _replace_placeholders(node, args, **kwargs):
4982        if isinstance(node, Placeholder):
4983            if node.name:
4984                new_name = kwargs.get(node.name)
4985                if new_name:
4986                    return to_identifier(new_name)
4987            else:
4988                try:
4989                    return to_identifier(next(args))
4990                except StopIteration:
4991                    pass
4992        return node
4993
4994    return expression.transform(_replace_placeholders, iter(args), **kwargs)
4995
4996
4997def expand(expression: Expression, sources: t.Dict[str, Subqueryable], copy=True) -> Expression:
4998    """Transforms an expression by expanding all referenced sources into subqueries.
4999
5000    Examples:
5001        >>> from sqlglot import parse_one
5002        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5003        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5004
5005    Args:
5006        expression: The expression to expand.
5007        sources: A dictionary of name to Subqueryables.
5008        copy: Whether or not to copy the expression during transformation. Defaults to True.
5009
5010    Returns:
5011        The transformed expression.
5012    """
5013
5014    def _expand(node: Expression):
5015        if isinstance(node, Table):
5016            name = table_name(node)
5017            source = sources.get(name)
5018            if source:
5019                subquery = source.subquery(node.alias or name)
5020                subquery.comments = [f"source: {name}"]
5021                return subquery
5022        return node
5023
5024    return expression.transform(_expand, copy=copy)
5025
5026
5027def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5028    """
5029    Returns a Func expression.
5030
5031    Examples:
5032        >>> func("abs", 5).sql()
5033        'ABS(5)'
5034
5035        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5036        'CAST(5 AS DOUBLE)'
5037
5038    Args:
5039        name: the name of the function to build.
5040        args: the args used to instantiate the function of interest.
5041        dialect: the source dialect.
5042        kwargs: the kwargs used to instantiate the function of interest.
5043
5044    Note:
5045        The arguments `args` and `kwargs` are mutually exclusive.
5046
5047    Returns:
5048        An instance of the function of interest, or an anonymous function, if `name` doesn't
5049        correspond to an existing `sqlglot.expressions.Func` class.
5050    """
5051    if args and kwargs:
5052        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5053
5054    from sqlglot.dialects.dialect import Dialect
5055
5056    converted = [convert(arg) for arg in args]
5057    kwargs = {key: convert(value) for key, value in kwargs.items()}
5058
5059    parser = Dialect.get_or_raise(dialect)().parser()
5060    from_args_list = parser.FUNCTIONS.get(name.upper())
5061
5062    if from_args_list:
5063        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5064    else:
5065        kwargs = kwargs or {"expressions": converted}
5066        function = Anonymous(this=name, **kwargs)
5067
5068    for error_message in function.error_messages(converted):
5069        raise ValueError(error_message)
5070
5071    return function
5072
5073
5074def true():
5075    """
5076    Returns a true Boolean expression.
5077    """
5078    return Boolean(this=True)
5079
5080
5081def false():
5082    """
5083    Returns a false Boolean expression.
5084    """
5085    return Boolean(this=False)
5086
5087
5088def null():
5089    """
5090    Returns a Null expression.
5091    """
5092    return Null()
5093
5094
5095# TODO: deprecate this
5096TRUE = Boolean(this=True)
5097FALSE = Boolean(this=False)
5098NULL = Null()
class Expression:
 56class Expression(metaclass=_Expression):
 57    """
 58    The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
 59    context, such as its child expressions, their names (arg keys), and whether a given child expression
 60    is optional or not.
 61
 62    Attributes:
 63        key: a unique key for each class in the Expression hierarchy. This is useful for hashing
 64            and representing expressions as strings.
 65        arg_types: determines what arguments (child nodes) are supported by an expression. It
 66            maps arg keys to booleans that indicate whether the corresponding args are optional.
 67
 68    Example:
 69        >>> class Foo(Expression):
 70        ...     arg_types = {"this": True, "expression": False}
 71
 72        The above definition informs us that Foo is an Expression that requires an argument called
 73        "this" and may also optionally receive an argument called "expression".
 74
 75    Args:
 76        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
 77        parent: a reference to the parent expression (or None, in case of root expressions).
 78        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
 79            uses to refer to it.
 80        comments: a list of comments that are associated with a given expression. This is used in
 81            order to preserve comments when transpiling SQL code.
 82        _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
 83            optimizer, in order to enable some transformations that require type information.
 84    """
 85
 86    key = "expression"
 87    arg_types = {"this": True}
 88    __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta")
 89
 90    def __init__(self, **args: t.Any):
 91        self.args: t.Dict[str, t.Any] = args
 92        self.parent: t.Optional[Expression] = None
 93        self.arg_key: t.Optional[str] = None
 94        self.comments: t.Optional[t.List[str]] = None
 95        self._type: t.Optional[DataType] = None
 96        self._meta: t.Optional[t.Dict[str, t.Any]] = None
 97
 98        for arg_key, value in self.args.items():
 99            self._set_parent(arg_key, value)
100
101    def __eq__(self, other) -> bool:
102        return type(self) is type(other) and _norm_args(self) == _norm_args(other)
103
104    def __hash__(self) -> int:
105        return hash(
106            (
107                self.key,
108                tuple(
109                    (k, tuple(v) if isinstance(v, list) else v) for k, v in _norm_args(self).items()
110                ),
111            )
112        )
113
114    @property
115    def this(self):
116        """
117        Retrieves the argument with key "this".
118        """
119        return self.args.get("this")
120
121    @property
122    def expression(self):
123        """
124        Retrieves the argument with key "expression".
125        """
126        return self.args.get("expression")
127
128    @property
129    def expressions(self):
130        """
131        Retrieves the argument with key "expressions".
132        """
133        return self.args.get("expressions") or []
134
135    def text(self, key) -> str:
136        """
137        Returns a textual representation of the argument corresponding to "key". This can only be used
138        for args that are strings or leaf Expression instances, such as identifiers and literals.
139        """
140        field = self.args.get(key)
141        if isinstance(field, str):
142            return field
143        if isinstance(field, (Identifier, Literal, Var)):
144            return field.this
145        if isinstance(field, (Star, Null)):
146            return field.name
147        return ""
148
149    @property
150    def is_string(self) -> bool:
151        """
152        Checks whether a Literal expression is a string.
153        """
154        return isinstance(self, Literal) and self.args["is_string"]
155
156    @property
157    def is_number(self) -> bool:
158        """
159        Checks whether a Literal expression is a number.
160        """
161        return isinstance(self, Literal) and not self.args["is_string"]
162
163    @property
164    def is_int(self) -> bool:
165        """
166        Checks whether a Literal expression is an integer.
167        """
168        if self.is_number:
169            try:
170                int(self.name)
171                return True
172            except ValueError:
173                pass
174        return False
175
176    @property
177    def is_star(self) -> bool:
178        """Checks whether an expression is a star."""
179        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
180
181    @property
182    def alias(self) -> str:
183        """
184        Returns the alias of the expression, or an empty string if it's not aliased.
185        """
186        if isinstance(self.args.get("alias"), TableAlias):
187            return self.args["alias"].name
188        return self.text("alias")
189
190    @property
191    def name(self) -> str:
192        return self.text("this")
193
194    @property
195    def alias_or_name(self):
196        return self.alias or self.name
197
198    @property
199    def output_name(self):
200        """
201        Name of the output column if this expression is a selection.
202
203        If the Expression has no output name, an empty string is returned.
204
205        Example:
206            >>> from sqlglot import parse_one
207            >>> parse_one("SELECT a").expressions[0].output_name
208            'a'
209            >>> parse_one("SELECT b AS c").expressions[0].output_name
210            'c'
211            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
212            ''
213        """
214        return ""
215
216    @property
217    def type(self) -> t.Optional[DataType]:
218        return self._type
219
220    @type.setter
221    def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None:
222        if dtype and not isinstance(dtype, DataType):
223            dtype = DataType.build(dtype)
224        self._type = dtype  # type: ignore
225
226    @property
227    def meta(self) -> t.Dict[str, t.Any]:
228        if self._meta is None:
229            self._meta = {}
230        return self._meta
231
232    def __deepcopy__(self, memo):
233        copy = self.__class__(**deepcopy(self.args))
234        if self.comments is not None:
235            copy.comments = deepcopy(self.comments)
236
237        if self._type is not None:
238            copy._type = self._type.copy()
239
240        if self._meta is not None:
241            copy._meta = deepcopy(self._meta)
242
243        return copy
244
245    def copy(self):
246        """
247        Returns a deep copy of the expression.
248        """
249        new = deepcopy(self)
250        new.parent = self.parent
251        for item, parent, _ in new.bfs():
252            if isinstance(item, Expression) and parent:
253                item.parent = parent
254        return new
255
256    def append(self, arg_key, value):
257        """
258        Appends value to arg_key if it's a list or sets it as a new list.
259
260        Args:
261            arg_key (str): name of the list expression arg
262            value (Any): value to append to the list
263        """
264        if not isinstance(self.args.get(arg_key), list):
265            self.args[arg_key] = []
266        self.args[arg_key].append(value)
267        self._set_parent(arg_key, value)
268
269    def set(self, arg_key, value):
270        """
271        Sets `arg_key` to `value`.
272
273        Args:
274            arg_key (str): name of the expression arg.
275            value: value to set the arg to.
276        """
277        self.args[arg_key] = value
278        self._set_parent(arg_key, value)
279
280    def _set_parent(self, arg_key, value):
281        if isinstance(value, Expression):
282            value.parent = self
283            value.arg_key = arg_key
284        elif isinstance(value, list):
285            for v in value:
286                if isinstance(v, Expression):
287                    v.parent = self
288                    v.arg_key = arg_key
289
290    @property
291    def depth(self):
292        """
293        Returns the depth of this tree.
294        """
295        if self.parent:
296            return self.parent.depth + 1
297        return 0
298
299    def find(self, *expression_types: t.Type[E], bfs=True) -> E | None:
300        """
301        Returns the first node in this tree which matches at least one of
302        the specified types.
303
304        Args:
305            expression_types: the expression type(s) to match.
306
307        Returns:
308            The node which matches the criteria or None if no such node was found.
309        """
310        return next(self.find_all(*expression_types, bfs=bfs), None)
311
312    def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]:
313        """
314        Returns a generator object which visits all nodes in this tree and only
315        yields those that match at least one of the specified expression types.
316
317        Args:
318            expression_types: the expression type(s) to match.
319
320        Returns:
321            The generator object.
322        """
323        for expression, _, _ in self.walk(bfs=bfs):
324            if isinstance(expression, expression_types):
325                yield expression
326
327    def find_ancestor(self, *expression_types: t.Type[E]) -> E | None:
328        """
329        Returns a nearest parent matching expression_types.
330
331        Args:
332            expression_types: the expression type(s) to match.
333
334        Returns:
335            The parent node.
336        """
337        ancestor = self.parent
338        while ancestor and not isinstance(ancestor, expression_types):
339            ancestor = ancestor.parent
340        return t.cast(E, ancestor)
341
342    @property
343    def parent_select(self):
344        """
345        Returns the parent select statement.
346        """
347        return self.find_ancestor(Select)
348
349    def root(self) -> Expression:
350        """
351        Returns the root expression of this tree.
352        """
353        expression = self
354        while expression.parent:
355            expression = expression.parent
356        return expression
357
358    def walk(self, bfs=True, prune=None):
359        """
360        Returns a generator object which visits all nodes in this tree.
361
362        Args:
363            bfs (bool): if set to True the BFS traversal order will be applied,
364                otherwise the DFS traversal will be used instead.
365            prune ((node, parent, arg_key) -> bool): callable that returns True if
366                the generator should stop traversing this branch of the tree.
367
368        Returns:
369            the generator object.
370        """
371        if bfs:
372            yield from self.bfs(prune=prune)
373        else:
374            yield from self.dfs(prune=prune)
375
376    def dfs(self, parent=None, key=None, prune=None):
377        """
378        Returns a generator object which visits all nodes in this tree in
379        the DFS (Depth-first) order.
380
381        Returns:
382            The generator object.
383        """
384        parent = parent or self.parent
385        yield self, parent, key
386        if prune and prune(self, parent, key):
387            return
388
389        for k, v in self.args.items():
390            for node in ensure_collection(v):
391                if isinstance(node, Expression):
392                    yield from node.dfs(self, k, prune)
393
394    def bfs(self, prune=None):
395        """
396        Returns a generator object which visits all nodes in this tree in
397        the BFS (Breadth-first) order.
398
399        Returns:
400            The generator object.
401        """
402        queue = deque([(self, self.parent, None)])
403
404        while queue:
405            item, parent, key = queue.popleft()
406
407            yield item, parent, key
408            if prune and prune(item, parent, key):
409                continue
410
411            if isinstance(item, Expression):
412                for k, v in item.args.items():
413                    for node in ensure_collection(v):
414                        if isinstance(node, Expression):
415                            queue.append((node, item, k))
416
417    def unnest(self):
418        """
419        Returns the first non parenthesis child or self.
420        """
421        expression = self
422        while isinstance(expression, Paren):
423            expression = expression.this
424        return expression
425
426    def unalias(self):
427        """
428        Returns the inner expression if this is an Alias.
429        """
430        if isinstance(self, Alias):
431            return self.this
432        return self
433
434    def unnest_operands(self):
435        """
436        Returns unnested operands as a tuple.
437        """
438        return tuple(arg.unnest() for arg in self.args.values() if arg)
439
440    def flatten(self, unnest=True):
441        """
442        Returns a generator which yields child nodes who's parents are the same class.
443
444        A AND B AND C -> [A, B, C]
445        """
446        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not isinstance(n, self.__class__)):
447            if not isinstance(node, self.__class__):
448                yield node.unnest() if unnest else node
449
450    def __str__(self):
451        return self.sql()
452
453    def __repr__(self):
454        return self._to_s()
455
456    def sql(self, dialect: DialectType = None, **opts) -> str:
457        """
458        Returns SQL string representation of this tree.
459
460        Args:
461            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
462            opts: other `sqlglot.generator.Generator` options.
463
464        Returns:
465            The SQL string.
466        """
467        from sqlglot.dialects import Dialect
468
469        return Dialect.get_or_raise(dialect)().generate(self, **opts)
470
471    def _to_s(self, hide_missing: bool = True, level: int = 0) -> str:
472        indent = "" if not level else "\n"
473        indent += "".join(["  "] * level)
474        left = f"({self.key.upper()} "
475
476        args: t.Dict[str, t.Any] = {
477            k: ", ".join(
478                v._to_s(hide_missing=hide_missing, level=level + 1)
479                if hasattr(v, "_to_s")
480                else str(v)
481                for v in ensure_collection(vs)
482                if v is not None
483            )
484            for k, vs in self.args.items()
485        }
486        args["comments"] = self.comments
487        args["type"] = self.type
488        args = {k: v for k, v in args.items() if v or not hide_missing}
489
490        right = ", ".join(f"{k}: {v}" for k, v in args.items())
491        right += ")"
492
493        return indent + left + right
494
495    def transform(self, fun, *args, copy=True, **kwargs):
496        """
497        Recursively visits all tree nodes (excluding already transformed ones)
498        and applies the given transformation function to each node.
499
500        Args:
501            fun (function): a function which takes a node as an argument and returns a
502                new transformed node or the same node without modifications. If the function
503                returns None, then the corresponding node will be removed from the syntax tree.
504            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
505                modified in place.
506
507        Returns:
508            The transformed tree.
509        """
510        node = self.copy() if copy else self
511        new_node = fun(node, *args, **kwargs)
512
513        if new_node is None or not isinstance(new_node, Expression):
514            return new_node
515        if new_node is not node:
516            new_node.parent = node.parent
517            return new_node
518
519        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
520        return new_node
521
522    def replace(self, expression):
523        """
524        Swap out this expression with a new expression.
525
526        For example::
527
528            >>> tree = Select().select("x").from_("tbl")
529            >>> tree.find(Column).replace(Column(this="y"))
530            (COLUMN this: y)
531            >>> tree.sql()
532            'SELECT y FROM tbl'
533
534        Args:
535            expression (Expression|None): new node
536
537        Returns:
538            The new expression or expressions.
539        """
540        if not self.parent:
541            return expression
542
543        parent = self.parent
544        self.parent = None
545
546        replace_children(parent, lambda child: expression if child is self else child)
547        return expression
548
549    def pop(self):
550        """
551        Remove this expression from its AST.
552
553        Returns:
554            The popped expression.
555        """
556        self.replace(None)
557        return self
558
559    def assert_is(self, type_):
560        """
561        Assert that this `Expression` is an instance of `type_`.
562
563        If it is NOT an instance of `type_`, this raises an assertion error.
564        Otherwise, this returns this expression.
565
566        Examples:
567            This is useful for type security in chained expressions:
568
569            >>> import sqlglot
570            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
571            'SELECT x, z FROM y'
572        """
573        assert isinstance(self, type_)
574        return self
575
576    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
577        """
578        Checks if this expression is valid (e.g. all mandatory args are set).
579
580        Args:
581            args: a sequence of values that were used to instantiate a Func expression. This is used
582                to check that the provided arguments don't exceed the function argument limit.
583
584        Returns:
585            A list of error messages for all possible errors that were found.
586        """
587        errors: t.List[str] = []
588
589        for k in self.args:
590            if k not in self.arg_types:
591                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
592        for k, mandatory in self.arg_types.items():
593            v = self.args.get(k)
594            if mandatory and (v is None or (isinstance(v, list) and not v)):
595                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
596
597        if (
598            args
599            and isinstance(self, Func)
600            and len(args) > len(self.arg_types)
601            and not self.is_var_len_args
602        ):
603            errors.append(
604                f"The number of provided arguments ({len(args)}) is greater than "
605                f"the maximum number of supported arguments ({len(self.arg_types)})"
606            )
607
608        return errors
609
610    def dump(self):
611        """
612        Dump this Expression to a JSON-serializable dict.
613        """
614        from sqlglot.serde import dump
615
616        return dump(self)
617
618    @classmethod
619    def load(cls, obj):
620        """
621        Load a dict (as returned by `Expression.dump`) into an Expression instance.
622        """
623        from sqlglot.serde import load
624
625        return load(obj)

The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary context, such as its child expressions, their names (arg keys), and whether a given child expression is optional or not.

Attributes:
  • key: a unique key for each class in the Expression hierarchy. This is useful for hashing and representing expressions as strings.
  • arg_types: determines what arguments (child nodes) are supported by an expression. It maps arg keys to booleans that indicate whether the corresponding args are optional.
Example:
>>> class Foo(Expression):
...     arg_types = {"this": True, "expression": False}

The above definition informs us that Foo is an Expression that requires an argument called "this" and may also optionally receive an argument called "expression".

Arguments:
  • args: a mapping used for retrieving the arguments of an expression, given their arg keys.
  • parent: a reference to the parent expression (or None, in case of root expressions).
  • arg_key: the arg key an expression is associated with, i.e. the name its parent expression uses to refer to it.
  • comments: a list of comments that are associated with a given expression. This is used in order to preserve comments when transpiling SQL code.
  • _type: the sqlglot.expressions.DataType type of an expression. This is inferred by the optimizer, in order to enable some transformations that require type information.
Expression(**args: Any)
90    def __init__(self, **args: t.Any):
91        self.args: t.Dict[str, t.Any] = args
92        self.parent: t.Optional[Expression] = None
93        self.arg_key: t.Optional[str] = None
94        self.comments: t.Optional[t.List[str]] = None
95        self._type: t.Optional[DataType] = None
96        self._meta: t.Optional[t.Dict[str, t.Any]] = None
97
98        for arg_key, value in self.args.items():
99            self._set_parent(arg_key, value)
this

Retrieves the argument with key "this".

expression

Retrieves the argument with key "expression".

expressions

Retrieves the argument with key "expressions".

def text(self, key) -> str:
135    def text(self, key) -> str:
136        """
137        Returns a textual representation of the argument corresponding to "key". This can only be used
138        for args that are strings or leaf Expression instances, such as identifiers and literals.
139        """
140        field = self.args.get(key)
141        if isinstance(field, str):
142            return field
143        if isinstance(field, (Identifier, Literal, Var)):
144            return field.this
145        if isinstance(field, (Star, Null)):
146            return field.name
147        return ""

Returns a textual representation of the argument corresponding to "key". This can only be used for args that are strings or leaf Expression instances, such as identifiers and literals.

is_string: bool

Checks whether a Literal expression is a string.

is_number: bool

Checks whether a Literal expression is a number.

is_int: bool

Checks whether a Literal expression is an integer.

is_star: bool

Checks whether an expression is a star.

alias: str

Returns the alias of the expression, or an empty string if it's not aliased.

output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
def copy(self):
245    def copy(self):
246        """
247        Returns a deep copy of the expression.
248        """
249        new = deepcopy(self)
250        new.parent = self.parent
251        for item, parent, _ in new.bfs():
252            if isinstance(item, Expression) and parent:
253                item.parent = parent
254        return new

Returns a deep copy of the expression.

def append(self, arg_key, value):
256    def append(self, arg_key, value):
257        """
258        Appends value to arg_key if it's a list or sets it as a new list.
259
260        Args:
261            arg_key (str): name of the list expression arg
262            value (Any): value to append to the list
263        """
264        if not isinstance(self.args.get(arg_key), list):
265            self.args[arg_key] = []
266        self.args[arg_key].append(value)
267        self._set_parent(arg_key, value)

Appends value to arg_key if it's a list or sets it as a new list.

Arguments:
  • arg_key (str): name of the list expression arg
  • value (Any): value to append to the list
def set(self, arg_key, value):
269    def set(self, arg_key, value):
270        """
271        Sets `arg_key` to `value`.
272
273        Args:
274            arg_key (str): name of the expression arg.
275            value: value to set the arg to.
276        """
277        self.args[arg_key] = value
278        self._set_parent(arg_key, value)

Sets arg_key to value.

Arguments:
  • arg_key (str): name of the expression arg.
  • value: value to set the arg to.
depth

Returns the depth of this tree.

def find(self, *expression_types: Type[~E], bfs=True) -> Optional[~E]:
299    def find(self, *expression_types: t.Type[E], bfs=True) -> E | None:
300        """
301        Returns the first node in this tree which matches at least one of
302        the specified types.
303
304        Args:
305            expression_types: the expression type(s) to match.
306
307        Returns:
308            The node which matches the criteria or None if no such node was found.
309        """
310        return next(self.find_all(*expression_types, bfs=bfs), None)

Returns the first node in this tree which matches at least one of the specified types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The node which matches the criteria or None if no such node was found.

def find_all(self, *expression_types: Type[~E], bfs=True) -> Iterator[~E]:
312    def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]:
313        """
314        Returns a generator object which visits all nodes in this tree and only
315        yields those that match at least one of the specified expression types.
316
317        Args:
318            expression_types: the expression type(s) to match.
319
320        Returns:
321            The generator object.
322        """
323        for expression, _, _ in self.walk(bfs=bfs):
324            if isinstance(expression, expression_types):
325                yield expression

Returns a generator object which visits all nodes in this tree and only yields those that match at least one of the specified expression types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The generator object.

def find_ancestor(self, *expression_types: Type[~E]) -> Optional[~E]:
327    def find_ancestor(self, *expression_types: t.Type[E]) -> E | None:
328        """
329        Returns a nearest parent matching expression_types.
330
331        Args:
332            expression_types: the expression type(s) to match.
333
334        Returns:
335            The parent node.
336        """
337        ancestor = self.parent
338        while ancestor and not isinstance(ancestor, expression_types):
339            ancestor = ancestor.parent
340        return t.cast(E, ancestor)

Returns a nearest parent matching expression_types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The parent node.

parent_select

Returns the parent select statement.

def root(self) -> sqlglot.expressions.Expression:
349    def root(self) -> Expression:
350        """
351        Returns the root expression of this tree.
352        """
353        expression = self
354        while expression.parent:
355            expression = expression.parent
356        return expression

Returns the root expression of this tree.

def walk(self, bfs=True, prune=None):
358    def walk(self, bfs=True, prune=None):
359        """
360        Returns a generator object which visits all nodes in this tree.
361
362        Args:
363            bfs (bool): if set to True the BFS traversal order will be applied,
364                otherwise the DFS traversal will be used instead.
365            prune ((node, parent, arg_key) -> bool): callable that returns True if
366                the generator should stop traversing this branch of the tree.
367
368        Returns:
369            the generator object.
370        """
371        if bfs:
372            yield from self.bfs(prune=prune)
373        else:
374            yield from self.dfs(prune=prune)

Returns a generator object which visits all nodes in this tree.

Arguments:
  • bfs (bool): if set to True the BFS traversal order will be applied, otherwise the DFS traversal will be used instead.
  • prune ((node, parent, arg_key) -> bool): callable that returns True if the generator should stop traversing this branch of the tree.
Returns:

the generator object.

def dfs(self, parent=None, key=None, prune=None):
376    def dfs(self, parent=None, key=None, prune=None):
377        """
378        Returns a generator object which visits all nodes in this tree in
379        the DFS (Depth-first) order.
380
381        Returns:
382            The generator object.
383        """
384        parent = parent or self.parent
385        yield self, parent, key
386        if prune and prune(self, parent, key):
387            return
388
389        for k, v in self.args.items():
390            for node in ensure_collection(v):
391                if isinstance(node, Expression):
392                    yield from node.dfs(self, k, prune)

Returns a generator object which visits all nodes in this tree in the DFS (Depth-first) order.

Returns:

The generator object.

def bfs(self, prune=None):
394    def bfs(self, prune=None):
395        """
396        Returns a generator object which visits all nodes in this tree in
397        the BFS (Breadth-first) order.
398
399        Returns:
400            The generator object.
401        """
402        queue = deque([(self, self.parent, None)])
403
404        while queue:
405            item, parent, key = queue.popleft()
406
407            yield item, parent, key
408            if prune and prune(item, parent, key):
409                continue
410
411            if isinstance(item, Expression):
412                for k, v in item.args.items():
413                    for node in ensure_collection(v):
414                        if isinstance(node, Expression):
415                            queue.append((node, item, k))

Returns a generator object which visits all nodes in this tree in the BFS (Breadth-first) order.

Returns:

The generator object.

def unnest(self):
417    def unnest(self):
418        """
419        Returns the first non parenthesis child or self.
420        """
421        expression = self
422        while isinstance(expression, Paren):
423            expression = expression.this
424        return expression

Returns the first non parenthesis child or self.

def unalias(self):
426    def unalias(self):
427        """
428        Returns the inner expression if this is an Alias.
429        """
430        if isinstance(self, Alias):
431            return self.this
432        return self

Returns the inner expression if this is an Alias.

def unnest_operands(self):
434    def unnest_operands(self):
435        """
436        Returns unnested operands as a tuple.
437        """
438        return tuple(arg.unnest() for arg in self.args.values() if arg)

Returns unnested operands as a tuple.

def flatten(self, unnest=True):
440    def flatten(self, unnest=True):
441        """
442        Returns a generator which yields child nodes who's parents are the same class.
443
444        A AND B AND C -> [A, B, C]
445        """
446        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not isinstance(n, self.__class__)):
447            if not isinstance(node, self.__class__):
448                yield node.unnest() if unnest else node

Returns a generator which yields child nodes who's parents are the same class.

A AND B AND C -> [A, B, C]

def sql( self, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> str:
456    def sql(self, dialect: DialectType = None, **opts) -> str:
457        """
458        Returns SQL string representation of this tree.
459
460        Args:
461            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
462            opts: other `sqlglot.generator.Generator` options.
463
464        Returns:
465            The SQL string.
466        """
467        from sqlglot.dialects import Dialect
468
469        return Dialect.get_or_raise(dialect)().generate(self, **opts)

Returns SQL string representation of this tree.

Arguments:
  • dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
  • opts: other sqlglot.generator.Generator options.
Returns:

The SQL string.

def transform(self, fun, *args, copy=True, **kwargs):
495    def transform(self, fun, *args, copy=True, **kwargs):
496        """
497        Recursively visits all tree nodes (excluding already transformed ones)
498        and applies the given transformation function to each node.
499
500        Args:
501            fun (function): a function which takes a node as an argument and returns a
502                new transformed node or the same node without modifications. If the function
503                returns None, then the corresponding node will be removed from the syntax tree.
504            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
505                modified in place.
506
507        Returns:
508            The transformed tree.
509        """
510        node = self.copy() if copy else self
511        new_node = fun(node, *args, **kwargs)
512
513        if new_node is None or not isinstance(new_node, Expression):
514            return new_node
515        if new_node is not node:
516            new_node.parent = node.parent
517            return new_node
518
519        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
520        return new_node

Recursively visits all tree nodes (excluding already transformed ones) and applies the given transformation function to each node.

Arguments:
  • fun (function): a function which takes a node as an argument and returns a new transformed node or the same node without modifications. If the function returns None, then the corresponding node will be removed from the syntax tree.
  • copy (bool): if set to True a new tree instance is constructed, otherwise the tree is modified in place.
Returns:

The transformed tree.

def replace(self, expression):
522    def replace(self, expression):
523        """
524        Swap out this expression with a new expression.
525
526        For example::
527
528            >>> tree = Select().select("x").from_("tbl")
529            >>> tree.find(Column).replace(Column(this="y"))
530            (COLUMN this: y)
531            >>> tree.sql()
532            'SELECT y FROM tbl'
533
534        Args:
535            expression (Expression|None): new node
536
537        Returns:
538            The new expression or expressions.
539        """
540        if not self.parent:
541            return expression
542
543        parent = self.parent
544        self.parent = None
545
546        replace_children(parent, lambda child: expression if child is self else child)
547        return expression

Swap out this expression with a new expression.

For example::

>>> tree = Select().select("x").from_("tbl")
>>> tree.find(Column).replace(Column(this="y"))
(COLUMN this: y)
>>> tree.sql()
'SELECT y FROM tbl'
Arguments:
  • expression (Expression|None): new node
Returns:

The new expression or expressions.

def pop(self):
549    def pop(self):
550        """
551        Remove this expression from its AST.
552
553        Returns:
554            The popped expression.
555        """
556        self.replace(None)
557        return self

Remove this expression from its AST.

Returns:

The popped expression.

def assert_is(self, type_):
559    def assert_is(self, type_):
560        """
561        Assert that this `Expression` is an instance of `type_`.
562
563        If it is NOT an instance of `type_`, this raises an assertion error.
564        Otherwise, this returns this expression.
565
566        Examples:
567            This is useful for type security in chained expressions:
568
569            >>> import sqlglot
570            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
571            'SELECT x, z FROM y'
572        """
573        assert isinstance(self, type_)
574        return self

Assert that this Expression is an instance of type_.

If it is NOT an instance of type_, this raises an assertion error. Otherwise, this returns this expression.

Examples:

This is useful for type security in chained expressions:

>>> import sqlglot
>>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
'SELECT x, z FROM y'
def error_messages(self, args: Optional[Sequence] = None) -> List[str]:
576    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
577        """
578        Checks if this expression is valid (e.g. all mandatory args are set).
579
580        Args:
581            args: a sequence of values that were used to instantiate a Func expression. This is used
582                to check that the provided arguments don't exceed the function argument limit.
583
584        Returns:
585            A list of error messages for all possible errors that were found.
586        """
587        errors: t.List[str] = []
588
589        for k in self.args:
590            if k not in self.arg_types:
591                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
592        for k, mandatory in self.arg_types.items():
593            v = self.args.get(k)
594            if mandatory and (v is None or (isinstance(v, list) and not v)):
595                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
596
597        if (
598            args
599            and isinstance(self, Func)
600            and len(args) > len(self.arg_types)
601            and not self.is_var_len_args
602        ):
603            errors.append(
604                f"The number of provided arguments ({len(args)}) is greater than "
605                f"the maximum number of supported arguments ({len(self.arg_types)})"
606            )
607
608        return errors

Checks if this expression is valid (e.g. all mandatory args are set).

Arguments:
  • args: a sequence of values that were used to instantiate a Func expression. This is used to check that the provided arguments don't exceed the function argument limit.
Returns:

A list of error messages for all possible errors that were found.

def dump(self):
610    def dump(self):
611        """
612        Dump this Expression to a JSON-serializable dict.
613        """
614        from sqlglot.serde import dump
615
616        return dump(self)

Dump this Expression to a JSON-serializable dict.

@classmethod
def load(cls, obj):
618    @classmethod
619    def load(cls, obj):
620        """
621        Load a dict (as returned by `Expression.dump`) into an Expression instance.
622        """
623        from sqlglot.serde import load
624
625        return load(obj)

Load a dict (as returned by Expression.dump) into an Expression instance.

class Condition(Expression):
636class Condition(Expression):
637    def and_(self, *expressions, dialect=None, **opts):
638        """
639        AND this condition with one or multiple expressions.
640
641        Example:
642            >>> condition("x=1").and_("y=1").sql()
643            'x = 1 AND y = 1'
644
645        Args:
646            *expressions (str | Expression): the SQL code strings to parse.
647                If an `Expression` instance is passed, it will be used as-is.
648            dialect (str): the dialect used to parse the input expression.
649            opts (kwargs): other options to use to parse the input expressions.
650
651        Returns:
652            And: the new condition.
653        """
654        return and_(self, *expressions, dialect=dialect, **opts)
655
656    def or_(self, *expressions, dialect=None, **opts):
657        """
658        OR this condition with one or multiple expressions.
659
660        Example:
661            >>> condition("x=1").or_("y=1").sql()
662            'x = 1 OR y = 1'
663
664        Args:
665            *expressions (str | Expression): the SQL code strings to parse.
666                If an `Expression` instance is passed, it will be used as-is.
667            dialect (str): the dialect used to parse the input expression.
668            opts (kwargs): other options to use to parse the input expressions.
669
670        Returns:
671            Or: the new condition.
672        """
673        return or_(self, *expressions, dialect=dialect, **opts)
674
675    def not_(self):
676        """
677        Wrap this condition with NOT.
678
679        Example:
680            >>> condition("x=1").not_().sql()
681            'NOT x = 1'
682
683        Returns:
684            Not: the new condition.
685        """
686        return not_(self)
def and_(self, *expressions, dialect=None, **opts):
637    def and_(self, *expressions, dialect=None, **opts):
638        """
639        AND this condition with one or multiple expressions.
640
641        Example:
642            >>> condition("x=1").and_("y=1").sql()
643            'x = 1 AND y = 1'
644
645        Args:
646            *expressions (str | Expression): the SQL code strings to parse.
647                If an `Expression` instance is passed, it will be used as-is.
648            dialect (str): the dialect used to parse the input expression.
649            opts (kwargs): other options to use to parse the input expressions.
650
651        Returns:
652            And: the new condition.
653        """
654        return and_(self, *expressions, dialect=dialect, **opts)

AND this condition with one or multiple expressions.

Example:
>>> condition("x=1").and_("y=1").sql()
'x = 1 AND y = 1'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

And: the new condition.

def or_(self, *expressions, dialect=None, **opts):
656    def or_(self, *expressions, dialect=None, **opts):
657        """
658        OR this condition with one or multiple expressions.
659
660        Example:
661            >>> condition("x=1").or_("y=1").sql()
662            'x = 1 OR y = 1'
663
664        Args:
665            *expressions (str | Expression): the SQL code strings to parse.
666                If an `Expression` instance is passed, it will be used as-is.
667            dialect (str): the dialect used to parse the input expression.
668            opts (kwargs): other options to use to parse the input expressions.
669
670        Returns:
671            Or: the new condition.
672        """
673        return or_(self, *expressions, dialect=dialect, **opts)

OR this condition with one or multiple expressions.

Example:
>>> condition("x=1").or_("y=1").sql()
'x = 1 OR y = 1'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Or: the new condition.

def not_(self):
675    def not_(self):
676        """
677        Wrap this condition with NOT.
678
679        Example:
680            >>> condition("x=1").not_().sql()
681            'NOT x = 1'
682
683        Returns:
684            Not: the new condition.
685        """
686        return not_(self)

Wrap this condition with NOT.

Example:
>>> condition("x=1").not_().sql()
'NOT x = 1'
Returns:

Not: the new condition.

class Predicate(Condition):
689class Predicate(Condition):
690    """Relationships like x = y, x > 1, x >= y."""

Relationships like x = y, x > 1, x >= y.

class DerivedTable(Expression):
693class DerivedTable(Expression):
694    @property
695    def alias_column_names(self):
696        table_alias = self.args.get("alias")
697        if not table_alias:
698            return []
699        column_list = table_alias.assert_is(TableAlias).args.get("columns") or []
700        return [c.name for c in column_list]
701
702    @property
703    def selects(self):
704        alias = self.args.get("alias")
705
706        if alias:
707            return alias.columns
708        return []
709
710    @property
711    def named_selects(self):
712        return [select.output_name for select in self.selects]
class Unionable(Expression):
715class Unionable(Expression):
716    def union(self, expression, distinct=True, dialect=None, **opts):
717        """
718        Builds a UNION expression.
719
720        Example:
721            >>> import sqlglot
722            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
723            'SELECT * FROM foo UNION SELECT * FROM bla'
724
725        Args:
726            expression (str | Expression): the SQL code string.
727                If an `Expression` instance is passed, it will be used as-is.
728            distinct (bool): set the DISTINCT flag if and only if this is true.
729            dialect (str): the dialect used to parse the input expression.
730            opts (kwargs): other options to use to parse the input expressions.
731        Returns:
732            Union: the Union expression.
733        """
734        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
735
736    def intersect(self, expression, distinct=True, dialect=None, **opts):
737        """
738        Builds an INTERSECT expression.
739
740        Example:
741            >>> import sqlglot
742            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
743            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
744
745        Args:
746            expression (str | Expression): the SQL code string.
747                If an `Expression` instance is passed, it will be used as-is.
748            distinct (bool): set the DISTINCT flag if and only if this is true.
749            dialect (str): the dialect used to parse the input expression.
750            opts (kwargs): other options to use to parse the input expressions.
751        Returns:
752            Intersect: the Intersect expression
753        """
754        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
755
756    def except_(self, expression, distinct=True, dialect=None, **opts):
757        """
758        Builds an EXCEPT expression.
759
760        Example:
761            >>> import sqlglot
762            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
763            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
764
765        Args:
766            expression (str | Expression): the SQL code string.
767                If an `Expression` instance is passed, it will be used as-is.
768            distinct (bool): set the DISTINCT flag if and only if this is true.
769            dialect (str): the dialect used to parse the input expression.
770            opts (kwargs): other options to use to parse the input expressions.
771        Returns:
772            Except: the Except expression
773        """
774        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
def union(self, expression, distinct=True, dialect=None, **opts):
716    def union(self, expression, distinct=True, dialect=None, **opts):
717        """
718        Builds a UNION expression.
719
720        Example:
721            >>> import sqlglot
722            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
723            'SELECT * FROM foo UNION SELECT * FROM bla'
724
725        Args:
726            expression (str | Expression): the SQL code string.
727                If an `Expression` instance is passed, it will be used as-is.
728            distinct (bool): set the DISTINCT flag if and only if this is true.
729            dialect (str): the dialect used to parse the input expression.
730            opts (kwargs): other options to use to parse the input expressions.
731        Returns:
732            Union: the Union expression.
733        """
734        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds a UNION expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • expression (str | Expression): the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Union: the Union expression.

def intersect(self, expression, distinct=True, dialect=None, **opts):
736    def intersect(self, expression, distinct=True, dialect=None, **opts):
737        """
738        Builds an INTERSECT expression.
739
740        Example:
741            >>> import sqlglot
742            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
743            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
744
745        Args:
746            expression (str | Expression): the SQL code string.
747                If an `Expression` instance is passed, it will be used as-is.
748            distinct (bool): set the DISTINCT flag if and only if this is true.
749            dialect (str): the dialect used to parse the input expression.
750            opts (kwargs): other options to use to parse the input expressions.
751        Returns:
752            Intersect: the Intersect expression
753        """
754        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an INTERSECT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • expression (str | Expression): the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Intersect: the Intersect expression

def except_(self, expression, distinct=True, dialect=None, **opts):
756    def except_(self, expression, distinct=True, dialect=None, **opts):
757        """
758        Builds an EXCEPT expression.
759
760        Example:
761            >>> import sqlglot
762            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
763            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
764
765        Args:
766            expression (str | Expression): the SQL code string.
767                If an `Expression` instance is passed, it will be used as-is.
768            distinct (bool): set the DISTINCT flag if and only if this is true.
769            dialect (str): the dialect used to parse the input expression.
770            opts (kwargs): other options to use to parse the input expressions.
771        Returns:
772            Except: the Except expression
773        """
774        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an EXCEPT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • expression (str | Expression): the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Except: the Except expression

class UDTF(DerivedTable, Unionable):
777class UDTF(DerivedTable, Unionable):
778    pass
class Cache(Expression):
781class Cache(Expression):
782    arg_types = {
783        "with": False,
784        "this": True,
785        "lazy": False,
786        "options": False,
787        "expression": False,
788    }
class Uncache(Expression):
791class Uncache(Expression):
792    arg_types = {"this": True, "exists": False}
class Create(Expression):
795class Create(Expression):
796    arg_types = {
797        "with": False,
798        "this": True,
799        "kind": True,
800        "expression": False,
801        "exists": False,
802        "properties": False,
803        "replace": False,
804        "unique": False,
805        "volatile": False,
806        "indexes": False,
807        "no_schema_binding": False,
808        "begin": False,
809    }
class Describe(Expression):
812class Describe(Expression):
813    arg_types = {"this": True, "kind": False}
class Set(Expression):
816class Set(Expression):
817    arg_types = {"expressions": False}
class SetItem(Expression):
820class SetItem(Expression):
821    arg_types = {
822        "this": False,
823        "expressions": False,
824        "kind": False,
825        "collate": False,  # MySQL SET NAMES statement
826        "global": False,
827    }
class Show(Expression):
830class Show(Expression):
831    arg_types = {
832        "this": True,
833        "target": False,
834        "offset": False,
835        "limit": False,
836        "like": False,
837        "where": False,
838        "db": False,
839        "full": False,
840        "mutex": False,
841        "query": False,
842        "channel": False,
843        "global": False,
844        "log": False,
845        "position": False,
846        "types": False,
847    }
class UserDefinedFunction(Expression):
850class UserDefinedFunction(Expression):
851    arg_types = {"this": True, "expressions": False, "wrapped": False}
class CharacterSet(Expression):
854class CharacterSet(Expression):
855    arg_types = {"this": True, "default": False}
class With(Expression):
858class With(Expression):
859    arg_types = {"expressions": True, "recursive": False}
860
861    @property
862    def recursive(self) -> bool:
863        return bool(self.args.get("recursive"))
class WithinGroup(Expression):
866class WithinGroup(Expression):
867    arg_types = {"this": True, "expression": False}
class CTE(DerivedTable):
870class CTE(DerivedTable):
871    arg_types = {"this": True, "alias": True}
class TableAlias(Expression):
874class TableAlias(Expression):
875    arg_types = {"this": False, "columns": False}
876
877    @property
878    def columns(self):
879        return self.args.get("columns") or []
class BitString(Condition):
882class BitString(Condition):
883    pass
class HexString(Condition):
886class HexString(Condition):
887    pass
class ByteString(Condition):
890class ByteString(Condition):
891    pass
class Column(Condition):
894class Column(Condition):
895    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
896
897    @property
898    def table(self) -> str:
899        return self.text("table")
900
901    @property
902    def db(self) -> str:
903        return self.text("db")
904
905    @property
906    def catalog(self) -> str:
907        return self.text("catalog")
908
909    @property
910    def output_name(self) -> str:
911        return self.name
912
913    @property
914    def parts(self) -> t.List[Identifier]:
915        """Return the parts of a column in order catalog, db, table, name."""
916        return [part for part in reversed(list(self.args.values())) if part]
917
918    def to_dot(self) -> Dot:
919        """Converts the column into a dot expression."""
920        parts = self.parts
921        parent = self.parent
922
923        while parent:
924            if isinstance(parent, Dot):
925                parts.append(parent.expression)
926            parent = parent.parent
927
928        return Dot.build(parts)
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''

Return the parts of a column in order catalog, db, table, name.

def to_dot(self) -> sqlglot.expressions.Dot:
918    def to_dot(self) -> Dot:
919        """Converts the column into a dot expression."""
920        parts = self.parts
921        parent = self.parent
922
923        while parent:
924            if isinstance(parent, Dot):
925                parts.append(parent.expression)
926            parent = parent.parent
927
928        return Dot.build(parts)

Converts the column into a dot expression.

class ColumnDef(Expression):
931class ColumnDef(Expression):
932    arg_types = {
933        "this": True,
934        "kind": False,
935        "constraints": False,
936        "exists": False,
937    }
class AlterColumn(Expression):
940class AlterColumn(Expression):
941    arg_types = {
942        "this": True,
943        "dtype": False,
944        "collate": False,
945        "using": False,
946        "default": False,
947        "drop": False,
948    }
class RenameTable(Expression):
951class RenameTable(Expression):
952    pass
class SetTag(Expression):
955class SetTag(Expression):
956    arg_types = {"expressions": True, "unset": False}
class Comment(Expression):
959class Comment(Expression):
960    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
class ColumnConstraint(Expression):
963class ColumnConstraint(Expression):
964    arg_types = {"this": False, "kind": True}
class ColumnConstraintKind(Expression):
967class ColumnConstraintKind(Expression):
968    pass
class AutoIncrementColumnConstraint(ColumnConstraintKind):
971class AutoIncrementColumnConstraint(ColumnConstraintKind):
972    pass
class CaseSpecificColumnConstraint(ColumnConstraintKind):
975class CaseSpecificColumnConstraint(ColumnConstraintKind):
976    arg_types = {"not_": True}
class CharacterSetColumnConstraint(ColumnConstraintKind):
979class CharacterSetColumnConstraint(ColumnConstraintKind):
980    arg_types = {"this": True}
class CheckColumnConstraint(ColumnConstraintKind):
983class CheckColumnConstraint(ColumnConstraintKind):
984    pass
class CollateColumnConstraint(ColumnConstraintKind):
987class CollateColumnConstraint(ColumnConstraintKind):
988    pass
class CommentColumnConstraint(ColumnConstraintKind):
991class CommentColumnConstraint(ColumnConstraintKind):
992    pass
class CompressColumnConstraint(ColumnConstraintKind):
995class CompressColumnConstraint(ColumnConstraintKind):
996    pass
class DateFormatColumnConstraint(ColumnConstraintKind):
 999class DateFormatColumnConstraint(ColumnConstraintKind):
1000    arg_types = {"this": True}
class DefaultColumnConstraint(ColumnConstraintKind):
1003class DefaultColumnConstraint(ColumnConstraintKind):
1004    pass
class EncodeColumnConstraint(ColumnConstraintKind):
1007class EncodeColumnConstraint(ColumnConstraintKind):
1008    pass
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1011class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1012    # this: True -> ALWAYS, this: False -> BY DEFAULT
1013    arg_types = {
1014        "this": False,
1015        "start": False,
1016        "increment": False,
1017        "minvalue": False,
1018        "maxvalue": False,
1019        "cycle": False,
1020    }
class InlineLengthColumnConstraint(ColumnConstraintKind):
1023class InlineLengthColumnConstraint(ColumnConstraintKind):
1024    pass
class NotNullColumnConstraint(ColumnConstraintKind):
1027class NotNullColumnConstraint(ColumnConstraintKind):
1028    arg_types = {"allow_null": False}
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1031class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1032    arg_types = {"desc": False}
class TitleColumnConstraint(ColumnConstraintKind):
1035class TitleColumnConstraint(ColumnConstraintKind):
1036    pass
class UniqueColumnConstraint(ColumnConstraintKind):
1039class UniqueColumnConstraint(ColumnConstraintKind):
1040    arg_types: t.Dict[str, t.Any] = {}
class UppercaseColumnConstraint(ColumnConstraintKind):
1043class UppercaseColumnConstraint(ColumnConstraintKind):
1044    arg_types: t.Dict[str, t.Any] = {}
class PathColumnConstraint(ColumnConstraintKind):
1047class PathColumnConstraint(ColumnConstraintKind):
1048    pass
class Constraint(Expression):
1051class Constraint(Expression):
1052    arg_types = {"this": True, "expressions": True}
class Delete(Expression):
1055class Delete(Expression):
1056    arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False}
1057
1058    def delete(
1059        self,
1060        table: ExpOrStr,
1061        dialect: DialectType = None,
1062        copy: bool = True,
1063        **opts,
1064    ) -> Delete:
1065        """
1066        Create a DELETE expression or replace the table on an existing DELETE expression.
1067
1068        Example:
1069            >>> delete("tbl").sql()
1070            'DELETE FROM tbl'
1071
1072        Args:
1073            table: the table from which to delete.
1074            dialect: the dialect used to parse the input expression.
1075            copy: if `False`, modify this expression instance in-place.
1076            opts: other options to use to parse the input expressions.
1077
1078        Returns:
1079            Delete: the modified expression.
1080        """
1081        return _apply_builder(
1082            expression=table,
1083            instance=self,
1084            arg="this",
1085            dialect=dialect,
1086            into=Table,
1087            copy=copy,
1088            **opts,
1089        )
1090
1091    def where(
1092        self,
1093        *expressions: ExpOrStr,
1094        append: bool = True,
1095        dialect: DialectType = None,
1096        copy: bool = True,
1097        **opts,
1098    ) -> Delete:
1099        """
1100        Append to or set the WHERE expressions.
1101
1102        Example:
1103            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1104            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1105
1106        Args:
1107            *expressions: the SQL code strings to parse.
1108                If an `Expression` instance is passed, it will be used as-is.
1109                Multiple expressions are combined with an AND operator.
1110            append: if `True`, AND the new expressions to any existing expression.
1111                Otherwise, this resets the expression.
1112            dialect: the dialect used to parse the input expressions.
1113            copy: if `False`, modify this expression instance in-place.
1114            opts: other options to use to parse the input expressions.
1115
1116        Returns:
1117            Delete: the modified expression.
1118        """
1119        return _apply_conjunction_builder(
1120            *expressions,
1121            instance=self,
1122            arg="where",
1123            append=append,
1124            into=Where,
1125            dialect=dialect,
1126            copy=copy,
1127            **opts,
1128        )
1129
1130    def returning(
1131        self,
1132        expression: ExpOrStr,
1133        dialect: DialectType = None,
1134        copy: bool = True,
1135        **opts,
1136    ) -> Delete:
1137        """
1138        Set the RETURNING expression. Not supported by all dialects.
1139
1140        Example:
1141            >>> delete("tbl").returning("*", dialect="postgres").sql()
1142            'DELETE FROM tbl RETURNING *'
1143
1144        Args:
1145            expression: the SQL code strings to parse.
1146                If an `Expression` instance is passed, it will be used as-is.
1147            dialect: the dialect used to parse the input expressions.
1148            copy: if `False`, modify this expression instance in-place.
1149            opts: other options to use to parse the input expressions.
1150
1151        Returns:
1152            Delete: the modified expression.
1153        """
1154        return _apply_builder(
1155            expression=expression,
1156            instance=self,
1157            arg="returning",
1158            prefix="RETURNING",
1159            dialect=dialect,
1160            copy=copy,
1161            into=Returning,
1162            **opts,
1163        )
def delete( self, table: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1058    def delete(
1059        self,
1060        table: ExpOrStr,
1061        dialect: DialectType = None,
1062        copy: bool = True,
1063        **opts,
1064    ) -> Delete:
1065        """
1066        Create a DELETE expression or replace the table on an existing DELETE expression.
1067
1068        Example:
1069            >>> delete("tbl").sql()
1070            'DELETE FROM tbl'
1071
1072        Args:
1073            table: the table from which to delete.
1074            dialect: the dialect used to parse the input expression.
1075            copy: if `False`, modify this expression instance in-place.
1076            opts: other options to use to parse the input expressions.
1077
1078        Returns:
1079            Delete: the modified expression.
1080        """
1081        return _apply_builder(
1082            expression=table,
1083            instance=self,
1084            arg="this",
1085            dialect=dialect,
1086            into=Table,
1087            copy=copy,
1088            **opts,
1089        )

Create a DELETE expression or replace the table on an existing DELETE expression.

Example:
>>> delete("tbl").sql()
'DELETE FROM tbl'
Arguments:
  • table: the table from which to delete.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

def where( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1091    def where(
1092        self,
1093        *expressions: ExpOrStr,
1094        append: bool = True,
1095        dialect: DialectType = None,
1096        copy: bool = True,
1097        **opts,
1098    ) -> Delete:
1099        """
1100        Append to or set the WHERE expressions.
1101
1102        Example:
1103            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1104            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1105
1106        Args:
1107            *expressions: the SQL code strings to parse.
1108                If an `Expression` instance is passed, it will be used as-is.
1109                Multiple expressions are combined with an AND operator.
1110            append: if `True`, AND the new expressions to any existing expression.
1111                Otherwise, this resets the expression.
1112            dialect: the dialect used to parse the input expressions.
1113            copy: if `False`, modify this expression instance in-place.
1114            opts: other options to use to parse the input expressions.
1115
1116        Returns:
1117            Delete: the modified expression.
1118        """
1119        return _apply_conjunction_builder(
1120            *expressions,
1121            instance=self,
1122            arg="where",
1123            append=append,
1124            into=Where,
1125            dialect=dialect,
1126            copy=copy,
1127            **opts,
1128        )

Append to or set the WHERE expressions.

Example:
>>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
"DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

def returning( self, expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1130    def returning(
1131        self,
1132        expression: ExpOrStr,
1133        dialect: DialectType = None,
1134        copy: bool = True,
1135        **opts,
1136    ) -> Delete:
1137        """
1138        Set the RETURNING expression. Not supported by all dialects.
1139
1140        Example:
1141            >>> delete("tbl").returning("*", dialect="postgres").sql()
1142            'DELETE FROM tbl RETURNING *'
1143
1144        Args:
1145            expression: the SQL code strings to parse.
1146                If an `Expression` instance is passed, it will be used as-is.
1147            dialect: the dialect used to parse the input expressions.
1148            copy: if `False`, modify this expression instance in-place.
1149            opts: other options to use to parse the input expressions.
1150
1151        Returns:
1152            Delete: the modified expression.
1153        """
1154        return _apply_builder(
1155            expression=expression,
1156            instance=self,
1157            arg="returning",
1158            prefix="RETURNING",
1159            dialect=dialect,
1160            copy=copy,
1161            into=Returning,
1162            **opts,
1163        )

Set the RETURNING expression. Not supported by all dialects.

Example:
>>> delete("tbl").returning("*", dialect="postgres").sql()
'DELETE FROM tbl RETURNING *'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

class Drop(Expression):
1166class Drop(Expression):
1167    arg_types = {
1168        "this": False,
1169        "kind": False,
1170        "exists": False,
1171        "temporary": False,
1172        "materialized": False,
1173        "cascade": False,
1174    }
class Filter(Expression):
1177class Filter(Expression):
1178    arg_types = {"this": True, "expression": True}
class Check(Expression):
1181class Check(Expression):
1182    pass
class Directory(Expression):
1185class Directory(Expression):
1186    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1187    arg_types = {"this": True, "local": False, "row_format": False}
class ForeignKey(Expression):
1190class ForeignKey(Expression):
1191    arg_types = {
1192        "expressions": True,
1193        "reference": False,
1194        "delete": False,
1195        "update": False,
1196    }
class PrimaryKey(Expression):
1199class PrimaryKey(Expression):
1200    arg_types = {"expressions": True, "options": False}
class Unique(Expression):
1203class Unique(Expression):
1204    arg_types = {"expressions": True}
class Into(Expression):
1209class Into(Expression):
1210    arg_types = {"this": True, "temporary": False, "unlogged": False}
class From(Expression):
1213class From(Expression):
1214    arg_types = {"expressions": True}
class Having(Expression):
1217class Having(Expression):
1218    pass
class Hint(Expression):
1221class Hint(Expression):
1222    arg_types = {"expressions": True}
class JoinHint(Expression):
1225class JoinHint(Expression):
1226    arg_types = {"this": True, "expressions": True}
class Identifier(Expression):
1229class Identifier(Expression):
1230    arg_types = {"this": True, "quoted": False}
1231
1232    @property
1233    def quoted(self):
1234        return bool(self.args.get("quoted"))
1235
1236    def __eq__(self, other):
1237        return isinstance(other, self.__class__) and _norm_arg(self.this) == _norm_arg(other.this)
1238
1239    def __hash__(self):
1240        return hash((self.key, self.this.lower()))
1241
1242    @property
1243    def output_name(self):
1244        return self.name
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Index(Expression):
1247class Index(Expression):
1248    arg_types = {
1249        "this": False,
1250        "table": False,
1251        "where": False,
1252        "columns": False,
1253        "unique": False,
1254        "primary": False,
1255        "amp": False,  # teradata
1256    }
class Insert(Expression):
1259class Insert(Expression):
1260    arg_types = {
1261        "with": False,
1262        "this": True,
1263        "expression": False,
1264        "returning": False,
1265        "overwrite": False,
1266        "exists": False,
1267        "partition": False,
1268        "alternative": False,
1269    }
class Returning(Expression):
1272class Returning(Expression):
1273    arg_types = {"expressions": True}
class Introducer(Expression):
1277class Introducer(Expression):
1278    arg_types = {"this": True, "expression": True}
class National(Expression):
1282class National(Expression):
1283    pass
class LoadData(Expression):
1286class LoadData(Expression):
1287    arg_types = {
1288        "this": True,
1289        "local": False,
1290        "overwrite": False,
1291        "inpath": True,
1292        "partition": False,
1293        "input_format": False,
1294        "serde": False,
1295    }
class Partition(Expression):
1298class Partition(Expression):
1299    arg_types = {"expressions": True}
class Fetch(Expression):
1302class Fetch(Expression):
1303    arg_types = {"direction": False, "count": False}
class Group(Expression):
1306class Group(Expression):
1307    arg_types = {
1308        "expressions": False,
1309        "grouping_sets": False,
1310        "cube": False,
1311        "rollup": False,
1312    }
class Lambda(Expression):
1315class Lambda(Expression):
1316    arg_types = {"this": True, "expressions": True}
class Limit(Expression):
1319class Limit(Expression):
1320    arg_types = {"this": False, "expression": True}
class Literal(Condition):
1323class Literal(Condition):
1324    arg_types = {"this": True, "is_string": True}
1325
1326    def __eq__(self, other):
1327        return (
1328            isinstance(other, Literal)
1329            and self.this == other.this
1330            and self.args["is_string"] == other.args["is_string"]
1331        )
1332
1333    def __hash__(self):
1334        return hash((self.key, self.this, self.args["is_string"]))
1335
1336    @classmethod
1337    def number(cls, number) -> Literal:
1338        return cls(this=str(number), is_string=False)
1339
1340    @classmethod
1341    def string(cls, string) -> Literal:
1342        return cls(this=str(string), is_string=True)
1343
1344    @property
1345    def output_name(self):
1346        return self.name
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1336    @classmethod
1337    def number(cls, number) -> Literal:
1338        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1340    @classmethod
1341    def string(cls, string) -> Literal:
1342        return cls(this=str(string), is_string=True)
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Join(Expression):
1349class Join(Expression):
1350    arg_types = {
1351        "this": True,
1352        "on": False,
1353        "side": False,
1354        "kind": False,
1355        "using": False,
1356        "natural": False,
1357    }
1358
1359    @property
1360    def kind(self):
1361        return self.text("kind").upper()
1362
1363    @property
1364    def side(self):
1365        return self.text("side").upper()
1366
1367    @property
1368    def alias_or_name(self):
1369        return self.this.alias_or_name
1370
1371    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1372        """
1373        Append to or set the ON expressions.
1374
1375        Example:
1376            >>> import sqlglot
1377            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1378            'JOIN x ON y = 1'
1379
1380        Args:
1381            *expressions (str | Expression): the SQL code strings to parse.
1382                If an `Expression` instance is passed, it will be used as-is.
1383                Multiple expressions are combined with an AND operator.
1384            append (bool): if `True`, AND the new expressions to any existing expression.
1385                Otherwise, this resets the expression.
1386            dialect (str): the dialect used to parse the input expressions.
1387            copy (bool): if `False`, modify this expression instance in-place.
1388            opts (kwargs): other options to use to parse the input expressions.
1389
1390        Returns:
1391            Join: the modified join expression.
1392        """
1393        join = _apply_conjunction_builder(
1394            *expressions,
1395            instance=self,
1396            arg="on",
1397            append=append,
1398            dialect=dialect,
1399            copy=copy,
1400            **opts,
1401        )
1402
1403        if join.kind == "CROSS":
1404            join.set("kind", None)
1405
1406        return join
1407
1408    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1409        """
1410        Append to or set the USING expressions.
1411
1412        Example:
1413            >>> import sqlglot
1414            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1415            'JOIN x USING (foo, bla)'
1416
1417        Args:
1418            *expressions (str | Expression): the SQL code strings to parse.
1419                If an `Expression` instance is passed, it will be used as-is.
1420            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1421                Otherwise, this resets the expression.
1422            dialect (str): the dialect used to parse the input expressions.
1423            copy (bool): if `False`, modify this expression instance in-place.
1424            opts (kwargs): other options to use to parse the input expressions.
1425
1426        Returns:
1427            Join: the modified join expression.
1428        """
1429        join = _apply_list_builder(
1430            *expressions,
1431            instance=self,
1432            arg="using",
1433            append=append,
1434            dialect=dialect,
1435            copy=copy,
1436            **opts,
1437        )
1438
1439        if join.kind == "CROSS":
1440            join.set("kind", None)
1441
1442        return join
def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1371    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1372        """
1373        Append to or set the ON expressions.
1374
1375        Example:
1376            >>> import sqlglot
1377            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1378            'JOIN x ON y = 1'
1379
1380        Args:
1381            *expressions (str | Expression): the SQL code strings to parse.
1382                If an `Expression` instance is passed, it will be used as-is.
1383                Multiple expressions are combined with an AND operator.
1384            append (bool): if `True`, AND the new expressions to any existing expression.
1385                Otherwise, this resets the expression.
1386            dialect (str): the dialect used to parse the input expressions.
1387            copy (bool): if `False`, modify this expression instance in-place.
1388            opts (kwargs): other options to use to parse the input expressions.
1389
1390        Returns:
1391            Join: the modified join expression.
1392        """
1393        join = _apply_conjunction_builder(
1394            *expressions,
1395            instance=self,
1396            arg="on",
1397            append=append,
1398            dialect=dialect,
1399            copy=copy,
1400            **opts,
1401        )
1402
1403        if join.kind == "CROSS":
1404            join.set("kind", None)
1405
1406        return join

Append to or set the ON expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
'JOIN x ON y = 1'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append (bool): if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Join: the modified join expression.

def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1408    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1409        """
1410        Append to or set the USING expressions.
1411
1412        Example:
1413            >>> import sqlglot
1414            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1415            'JOIN x USING (foo, bla)'
1416
1417        Args:
1418            *expressions (str | Expression): the SQL code strings to parse.
1419                If an `Expression` instance is passed, it will be used as-is.
1420            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1421                Otherwise, this resets the expression.
1422            dialect (str): the dialect used to parse the input expressions.
1423            copy (bool): if `False`, modify this expression instance in-place.
1424            opts (kwargs): other options to use to parse the input expressions.
1425
1426        Returns:
1427            Join: the modified join expression.
1428        """
1429        join = _apply_list_builder(
1430            *expressions,
1431            instance=self,
1432            arg="using",
1433            append=append,
1434            dialect=dialect,
1435            copy=copy,
1436            **opts,
1437        )
1438
1439        if join.kind == "CROSS":
1440            join.set("kind", None)
1441
1442        return join

Append to or set the USING expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
'JOIN x USING (foo, bla)'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append (bool): if True, concatenate the new expressions to the existing "using" list. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Join: the modified join expression.

class Lateral(UDTF):
1445class Lateral(UDTF):
1446    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
class MatchRecognize(Expression):
1449class MatchRecognize(Expression):
1450    arg_types = {
1451        "partition_by": False,
1452        "order": False,
1453        "measures": False,
1454        "rows": False,
1455        "after": False,
1456        "pattern": False,
1457        "define": False,
1458    }
class Final(Expression):
1463class Final(Expression):
1464    pass
class Offset(Expression):
1467class Offset(Expression):
1468    arg_types = {"this": False, "expression": True}
class Order(Expression):
1471class Order(Expression):
1472    arg_types = {"this": False, "expressions": True}
class Cluster(Order):
1477class Cluster(Order):
1478    pass
class Distribute(Order):
1481class Distribute(Order):
1482    pass
class Sort(Order):
1485class Sort(Order):
1486    pass
class Ordered(Expression):
1489class Ordered(Expression):
1490    arg_types = {"this": True, "desc": True, "nulls_first": True}
class Property(Expression):
1493class Property(Expression):
1494    arg_types = {"this": True, "value": True}
class AfterJournalProperty(Property):
1497class AfterJournalProperty(Property):
1498    arg_types = {"no": True, "dual": False, "local": False}
class AlgorithmProperty(Property):
1501class AlgorithmProperty(Property):
1502    arg_types = {"this": True}
class AutoIncrementProperty(Property):
1505class AutoIncrementProperty(Property):
1506    arg_types = {"this": True}
class BlockCompressionProperty(Property):
1509class BlockCompressionProperty(Property):
1510    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
class CharacterSetProperty(Property):
1513class CharacterSetProperty(Property):
1514    arg_types = {"this": True, "default": True}
class ChecksumProperty(Property):
1517class ChecksumProperty(Property):
1518    arg_types = {"on": False, "default": False}
class CollateProperty(Property):
1521class CollateProperty(Property):
1522    arg_types = {"this": True}
class DataBlocksizeProperty(Property):
1525class DataBlocksizeProperty(Property):
1526    arg_types = {"size": False, "units": False, "min": False, "default": False}
class DefinerProperty(Property):
1529class DefinerProperty(Property):
1530    arg_types = {"this": True}
class DistKeyProperty(Property):
1533class DistKeyProperty(Property):
1534    arg_types = {"this": True}
class DistStyleProperty(Property):
1537class DistStyleProperty(Property):
1538    arg_types = {"this": True}
class EngineProperty(Property):
1541class EngineProperty(Property):
1542    arg_types = {"this": True}
class ExecuteAsProperty(Property):
1545class ExecuteAsProperty(Property):
1546    arg_types = {"this": True}
class ExternalProperty(Property):
1549class ExternalProperty(Property):
1550    arg_types = {"this": False}
class FallbackProperty(Property):
1553class FallbackProperty(Property):
1554    arg_types = {"no": True, "protection": False}
class FileFormatProperty(Property):
1557class FileFormatProperty(Property):
1558    arg_types = {"this": True}
class FreespaceProperty(Property):
1561class FreespaceProperty(Property):
1562    arg_types = {"this": True, "percent": False}
class IsolatedLoadingProperty(Property):
1565class IsolatedLoadingProperty(Property):
1566    arg_types = {
1567        "no": True,
1568        "concurrent": True,
1569        "for_all": True,
1570        "for_insert": True,
1571        "for_none": True,
1572    }
class JournalProperty(Property):
1575class JournalProperty(Property):
1576    arg_types = {"no": True, "dual": False, "before": False}
class LanguageProperty(Property):
1579class LanguageProperty(Property):
1580    arg_types = {"this": True}
class LikeProperty(Property):
1583class LikeProperty(Property):
1584    arg_types = {"this": True, "expressions": False}
class LocationProperty(Property):
1587class LocationProperty(Property):
1588    arg_types = {"this": True}
class LockingProperty(Property):
1591class LockingProperty(Property):
1592    arg_types = {
1593        "this": False,
1594        "kind": True,
1595        "for_or_in": True,
1596        "lock_type": True,
1597        "override": False,
1598    }
class LogProperty(Property):
1601class LogProperty(Property):
1602    arg_types = {"no": True}
class MaterializedProperty(Property):
1605class MaterializedProperty(Property):
1606    arg_types = {"this": False}
class MergeBlockRatioProperty(Property):
1609class MergeBlockRatioProperty(Property):
1610    arg_types = {"this": False, "no": False, "default": False, "percent": False}
class NoPrimaryIndexProperty(Property):
1613class NoPrimaryIndexProperty(Property):
1614    arg_types = {"this": False}
class OnCommitProperty(Property):
1617class OnCommitProperty(Property):
1618    arg_type = {"this": False}
class PartitionedByProperty(Property):
1621class PartitionedByProperty(Property):
1622    arg_types = {"this": True}
class ReturnsProperty(Property):
1625class ReturnsProperty(Property):
1626    arg_types = {"this": True, "is_table": False, "table": False}
class RowFormatDelimitedProperty(Property):
1629class RowFormatDelimitedProperty(Property):
1630    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
1631    arg_types = {
1632        "fields": False,
1633        "escaped": False,
1634        "collection_items": False,
1635        "map_keys": False,
1636        "lines": False,
1637        "null": False,
1638        "serde": False,
1639    }
class RowFormatSerdeProperty(Property):
1642class RowFormatSerdeProperty(Property):
1643    arg_types = {"this": True}
class SchemaCommentProperty(Property):
1646class SchemaCommentProperty(Property):
1647    arg_types = {"this": True}
class SerdeProperties(Property):
1650class SerdeProperties(Property):
1651    arg_types = {"expressions": True}
class SetProperty(Property):
1654class SetProperty(Property):
1655    arg_types = {"multi": True}
class SortKeyProperty(Property):
1658class SortKeyProperty(Property):
1659    arg_types = {"this": True, "compound": False}
class SqlSecurityProperty(Property):
1662class SqlSecurityProperty(Property):
1663    arg_types = {"definer": True}
class TableFormatProperty(Property):
1666class TableFormatProperty(Property):
1667    arg_types = {"this": True}
class TemporaryProperty(Property):
1670class TemporaryProperty(Property):
1671    arg_types = {"global_": True}
class TransientProperty(Property):
1674class TransientProperty(Property):
1675    arg_types = {"this": False}
class VolatilityProperty(Property):
1678class VolatilityProperty(Property):
1679    arg_types = {"this": True}
class WithDataProperty(Property):
1682class WithDataProperty(Property):
1683    arg_types = {"no": True, "statistics": False}
class WithJournalTableProperty(Property):
1686class WithJournalTableProperty(Property):
1687    arg_types = {"this": True}
class Properties(Expression):
1690class Properties(Expression):
1691    arg_types = {"expressions": True}
1692
1693    NAME_TO_PROPERTY = {
1694        "ALGORITHM": AlgorithmProperty,
1695        "AUTO_INCREMENT": AutoIncrementProperty,
1696        "CHARACTER SET": CharacterSetProperty,
1697        "COLLATE": CollateProperty,
1698        "COMMENT": SchemaCommentProperty,
1699        "DEFINER": DefinerProperty,
1700        "DISTKEY": DistKeyProperty,
1701        "DISTSTYLE": DistStyleProperty,
1702        "ENGINE": EngineProperty,
1703        "EXECUTE AS": ExecuteAsProperty,
1704        "FORMAT": FileFormatProperty,
1705        "LANGUAGE": LanguageProperty,
1706        "LOCATION": LocationProperty,
1707        "PARTITIONED_BY": PartitionedByProperty,
1708        "RETURNS": ReturnsProperty,
1709        "SORTKEY": SortKeyProperty,
1710        "TABLE_FORMAT": TableFormatProperty,
1711    }
1712
1713    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
1714
1715    # CREATE property locations
1716    # Form: schema specified
1717    #   create [POST_CREATE]
1718    #     table a [POST_NAME]
1719    #     (b int) [POST_SCHEMA]
1720    #     with ([POST_WITH])
1721    #     index (b) [POST_INDEX]
1722    #
1723    # Form: alias selection
1724    #   create [POST_CREATE]
1725    #     table a [POST_NAME]
1726    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
1727    #     index (c) [POST_INDEX]
1728    class Location(AutoName):
1729        POST_CREATE = auto()
1730        POST_NAME = auto()
1731        POST_SCHEMA = auto()
1732        POST_WITH = auto()
1733        POST_ALIAS = auto()
1734        POST_EXPRESSION = auto()
1735        POST_INDEX = auto()
1736        UNSUPPORTED = auto()
1737
1738    @classmethod
1739    def from_dict(cls, properties_dict) -> Properties:
1740        expressions = []
1741        for key, value in properties_dict.items():
1742            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1743            if property_cls:
1744                expressions.append(property_cls(this=convert(value)))
1745            else:
1746                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1747
1748        return cls(expressions=expressions)
@classmethod
def from_dict(cls, properties_dict) -> sqlglot.expressions.Properties:
1738    @classmethod
1739    def from_dict(cls, properties_dict) -> Properties:
1740        expressions = []
1741        for key, value in properties_dict.items():
1742            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1743            if property_cls:
1744                expressions.append(property_cls(this=convert(value)))
1745            else:
1746                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1747
1748        return cls(expressions=expressions)
class Properties.Location(sqlglot.helper.AutoName):
1728    class Location(AutoName):
1729        POST_CREATE = auto()
1730        POST_NAME = auto()
1731        POST_SCHEMA = auto()
1732        POST_WITH = auto()
1733        POST_ALIAS = auto()
1734        POST_EXPRESSION = auto()
1735        POST_INDEX = auto()
1736        UNSUPPORTED = auto()

An enumeration.

POST_CREATE = <Location.POST_CREATE: 'POST_CREATE'>
POST_NAME = <Location.POST_NAME: 'POST_NAME'>
POST_SCHEMA = <Location.POST_SCHEMA: 'POST_SCHEMA'>
POST_WITH = <Location.POST_WITH: 'POST_WITH'>
POST_ALIAS = <Location.POST_ALIAS: 'POST_ALIAS'>
POST_EXPRESSION = <Location.POST_EXPRESSION: 'POST_EXPRESSION'>
POST_INDEX = <Location.POST_INDEX: 'POST_INDEX'>
UNSUPPORTED = <Location.UNSUPPORTED: 'UNSUPPORTED'>
Inherited Members
enum.Enum
name
value
class Qualify(Expression):
1751class Qualify(Expression):
1752    pass
class Return(Expression):
1756class Return(Expression):
1757    pass
class Reference(Expression):
1760class Reference(Expression):
1761    arg_types = {"this": True, "expressions": False, "options": False}
class Tuple(Expression):
1764class Tuple(Expression):
1765    arg_types = {"expressions": False}
class Subqueryable(Unionable):
1768class Subqueryable(Unionable):
1769    def subquery(self, alias=None, copy=True) -> Subquery:
1770        """
1771        Convert this expression to an aliased expression that can be used as a Subquery.
1772
1773        Example:
1774            >>> subquery = Select().select("x").from_("tbl").subquery()
1775            >>> Select().select("x").from_(subquery).sql()
1776            'SELECT x FROM (SELECT x FROM tbl)'
1777
1778        Args:
1779            alias (str | Identifier): an optional alias for the subquery
1780            copy (bool): if `False`, modify this expression instance in-place.
1781
1782        Returns:
1783            Alias: the subquery
1784        """
1785        instance = _maybe_copy(self, copy)
1786        return Subquery(
1787            this=instance,
1788            alias=TableAlias(this=to_identifier(alias)),
1789        )
1790
1791    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1792        raise NotImplementedError
1793
1794    @property
1795    def ctes(self):
1796        with_ = self.args.get("with")
1797        if not with_:
1798            return []
1799        return with_.expressions
1800
1801    @property
1802    def selects(self):
1803        raise NotImplementedError("Subqueryable objects must implement `selects`")
1804
1805    @property
1806    def named_selects(self):
1807        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
1808
1809    def with_(
1810        self,
1811        alias,
1812        as_,
1813        recursive=None,
1814        append=True,
1815        dialect=None,
1816        copy=True,
1817        **opts,
1818    ):
1819        """
1820        Append to or set the common table expressions.
1821
1822        Example:
1823            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
1824            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
1825
1826        Args:
1827            alias (str | Expression): the SQL code string to parse as the table name.
1828                If an `Expression` instance is passed, this is used as-is.
1829            as_ (str | Expression): the SQL code string to parse as the table expression.
1830                If an `Expression` instance is passed, it will be used as-is.
1831            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
1832            append (bool): if `True`, add to any existing expressions.
1833                Otherwise, this resets the expressions.
1834            dialect (str): the dialect used to parse the input expression.
1835            copy (bool): if `False`, modify this expression instance in-place.
1836            opts (kwargs): other options to use to parse the input expressions.
1837
1838        Returns:
1839            Select: the modified expression.
1840        """
1841        alias_expression = maybe_parse(
1842            alias,
1843            dialect=dialect,
1844            into=TableAlias,
1845            **opts,
1846        )
1847        as_expression = maybe_parse(
1848            as_,
1849            dialect=dialect,
1850            **opts,
1851        )
1852        cte = CTE(
1853            this=as_expression,
1854            alias=alias_expression,
1855        )
1856        return _apply_child_list_builder(
1857            cte,
1858            instance=self,
1859            arg="with",
1860            append=append,
1861            copy=copy,
1862            into=With,
1863            properties={"recursive": recursive or False},
1864        )
def subquery(self, alias=None, copy=True) -> sqlglot.expressions.Subquery:
1769    def subquery(self, alias=None, copy=True) -> Subquery:
1770        """
1771        Convert this expression to an aliased expression that can be used as a Subquery.
1772
1773        Example:
1774            >>> subquery = Select().select("x").from_("tbl").subquery()
1775            >>> Select().select("x").from_(subquery).sql()
1776            'SELECT x FROM (SELECT x FROM tbl)'
1777
1778        Args:
1779            alias (str | Identifier): an optional alias for the subquery
1780            copy (bool): if `False`, modify this expression instance in-place.
1781
1782        Returns:
1783            Alias: the subquery
1784        """
1785        instance = _maybe_copy(self, copy)
1786        return Subquery(
1787            this=instance,
1788            alias=TableAlias(this=to_identifier(alias)),
1789        )

Convert this expression to an aliased expression that can be used as a Subquery.

Example:
>>> subquery = Select().select("x").from_("tbl").subquery()
>>> Select().select("x").from_(subquery).sql()
'SELECT x FROM (SELECT x FROM tbl)'
Arguments:
  • alias (str | Identifier): an optional alias for the subquery
  • copy (bool): if False, modify this expression instance in-place.
Returns:

Alias: the subquery

def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
1791    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1792        raise NotImplementedError
def with_( self, alias, as_, recursive=None, append=True, dialect=None, copy=True, **opts):
1809    def with_(
1810        self,
1811        alias,
1812        as_,
1813        recursive=None,
1814        append=True,
1815        dialect=None,
1816        copy=True,
1817        **opts,
1818    ):
1819        """
1820        Append to or set the common table expressions.
1821
1822        Example:
1823            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
1824            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
1825
1826        Args:
1827            alias (str | Expression): the SQL code string to parse as the table name.
1828                If an `Expression` instance is passed, this is used as-is.
1829            as_ (str | Expression): the SQL code string to parse as the table expression.
1830                If an `Expression` instance is passed, it will be used as-is.
1831            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
1832            append (bool): if `True`, add to any existing expressions.
1833                Otherwise, this resets the expressions.
1834            dialect (str): the dialect used to parse the input expression.
1835            copy (bool): if `False`, modify this expression instance in-place.
1836            opts (kwargs): other options to use to parse the input expressions.
1837
1838        Returns:
1839            Select: the modified expression.
1840        """
1841        alias_expression = maybe_parse(
1842            alias,
1843            dialect=dialect,
1844            into=TableAlias,
1845            **opts,
1846        )
1847        as_expression = maybe_parse(
1848            as_,
1849            dialect=dialect,
1850            **opts,
1851        )
1852        cte = CTE(
1853            this=as_expression,
1854            alias=alias_expression,
1855        )
1856        return _apply_child_list_builder(
1857            cte,
1858            instance=self,
1859            arg="with",
1860            append=append,
1861            copy=copy,
1862            into=With,
1863            properties={"recursive": recursive or False},
1864        )

Append to or set the common table expressions.

Example:
>>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
Arguments:
  • alias (str | Expression): the SQL code string to parse as the table name. If an Expression instance is passed, this is used as-is.
  • as_ (str | Expression): the SQL code string to parse as the table expression. If an Expression instance is passed, it will be used as-is.
  • recursive (bool): set the RECURSIVE part of the expression. Defaults to False.
  • append (bool): if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

class Table(Expression):
1888class Table(Expression):
1889    arg_types = {
1890        "this": True,
1891        "alias": False,
1892        "db": False,
1893        "catalog": False,
1894        "laterals": False,
1895        "joins": False,
1896        "pivots": False,
1897        "hints": False,
1898        "system_time": False,
1899    }
1900
1901    @property
1902    def db(self) -> str:
1903        return self.text("db")
1904
1905    @property
1906    def catalog(self) -> str:
1907        return self.text("catalog")
class SystemTime(Expression):
1911class SystemTime(Expression):
1912    arg_types = {
1913        "this": False,
1914        "expression": False,
1915        "kind": True,
1916    }
class Union(Subqueryable):
1919class Union(Subqueryable):
1920    arg_types = {
1921        "with": False,
1922        "this": True,
1923        "expression": True,
1924        "distinct": False,
1925        **QUERY_MODIFIERS,
1926    }
1927
1928    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1929        """
1930        Set the LIMIT expression.
1931
1932        Example:
1933            >>> select("1").union(select("1")).limit(1).sql()
1934            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
1935
1936        Args:
1937            expression (str | int | Expression): the SQL code string to parse.
1938                This can also be an integer.
1939                If a `Limit` instance is passed, this is used as-is.
1940                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
1941            dialect (str): the dialect used to parse the input expression.
1942            copy (bool): if `False`, modify this expression instance in-place.
1943            opts (kwargs): other options to use to parse the input expressions.
1944
1945        Returns:
1946            Select: The limited subqueryable.
1947        """
1948        return (
1949            select("*")
1950            .from_(self.subquery(alias="_l_0", copy=copy))
1951            .limit(expression, dialect=dialect, copy=False, **opts)
1952        )
1953
1954    def select(
1955        self,
1956        *expressions: ExpOrStr,
1957        append: bool = True,
1958        dialect: DialectType = None,
1959        copy: bool = True,
1960        **opts,
1961    ) -> Union:
1962        """Append to or set the SELECT of the union recursively.
1963
1964        Example:
1965            >>> from sqlglot import parse_one
1966            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
1967            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
1968
1969        Args:
1970            *expressions: the SQL code strings to parse.
1971                If an `Expression` instance is passed, it will be used as-is.
1972            append: if `True`, add to any existing expressions.
1973                Otherwise, this resets the expressions.
1974            dialect: the dialect used to parse the input expressions.
1975            copy: if `False`, modify this expression instance in-place.
1976            opts: other options to use to parse the input expressions.
1977
1978        Returns:
1979            Union: the modified expression.
1980        """
1981        this = self.copy() if copy else self
1982        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
1983        this.expression.unnest().select(
1984            *expressions, append=append, dialect=dialect, copy=False, **opts
1985        )
1986        return this
1987
1988    @property
1989    def named_selects(self):
1990        return self.this.unnest().named_selects
1991
1992    @property
1993    def is_star(self) -> bool:
1994        return self.this.is_star or self.expression.is_star
1995
1996    @property
1997    def selects(self):
1998        return self.this.unnest().selects
1999
2000    @property
2001    def left(self):
2002        return self.this
2003
2004    @property
2005    def right(self):
2006        return self.expression
def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
1928    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1929        """
1930        Set the LIMIT expression.
1931
1932        Example:
1933            >>> select("1").union(select("1")).limit(1).sql()
1934            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
1935
1936        Args:
1937            expression (str | int | Expression): the SQL code string to parse.
1938                This can also be an integer.
1939                If a `Limit` instance is passed, this is used as-is.
1940                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
1941            dialect (str): the dialect used to parse the input expression.
1942            copy (bool): if `False`, modify this expression instance in-place.
1943            opts (kwargs): other options to use to parse the input expressions.
1944
1945        Returns:
1946            Select: The limited subqueryable.
1947        """
1948        return (
1949            select("*")
1950            .from_(self.subquery(alias="_l_0", copy=copy))
1951            .limit(expression, dialect=dialect, copy=False, **opts)
1952        )

Set the LIMIT expression.

Example:
>>> select("1").union(select("1")).limit(1).sql()
'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
Arguments:
  • expression (str | int | Expression): the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: The limited subqueryable.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Union:
1954    def select(
1955        self,
1956        *expressions: ExpOrStr,
1957        append: bool = True,
1958        dialect: DialectType = None,
1959        copy: bool = True,
1960        **opts,
1961    ) -> Union:
1962        """Append to or set the SELECT of the union recursively.
1963
1964        Example:
1965            >>> from sqlglot import parse_one
1966            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
1967            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
1968
1969        Args:
1970            *expressions: the SQL code strings to parse.
1971                If an `Expression` instance is passed, it will be used as-is.
1972            append: if `True`, add to any existing expressions.
1973                Otherwise, this resets the expressions.
1974            dialect: the dialect used to parse the input expressions.
1975            copy: if `False`, modify this expression instance in-place.
1976            opts: other options to use to parse the input expressions.
1977
1978        Returns:
1979            Union: the modified expression.
1980        """
1981        this = self.copy() if copy else self
1982        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
1983        this.expression.unnest().select(
1984            *expressions, append=append, dialect=dialect, copy=False, **opts
1985        )
1986        return this

Append to or set the SELECT of the union recursively.

Example:
>>> from sqlglot import parse_one
>>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Union: the modified expression.

is_star: bool

Checks whether an expression is a star.

class Except(Union):
2009class Except(Union):
2010    pass
class Intersect(Union):
2013class Intersect(Union):
2014    pass
class Unnest(UDTF):
2017class Unnest(UDTF):
2018    arg_types = {
2019        "expressions": True,
2020        "ordinality": False,
2021        "alias": False,
2022        "offset": False,
2023    }
class Update(Expression):
2026class Update(Expression):
2027    arg_types = {
2028        "with": False,
2029        "this": False,
2030        "expressions": True,
2031        "from": False,
2032        "where": False,
2033        "returning": False,
2034    }
class Values(UDTF):
2037class Values(UDTF):
2038    arg_types = {
2039        "expressions": True,
2040        "ordinality": False,
2041        "alias": False,
2042    }
class Var(Expression):
2045class Var(Expression):
2046    pass
class Schema(Expression):
2049class Schema(Expression):
2050    arg_types = {"this": False, "expressions": False}
class Lock(Expression):
2055class Lock(Expression):
2056    arg_types = {"update": True}
class Select(Subqueryable):
2059class Select(Subqueryable):
2060    arg_types = {
2061        "with": False,
2062        "expressions": False,
2063        "hint": False,
2064        "distinct": False,
2065        "into": False,
2066        "from": False,
2067        **QUERY_MODIFIERS,
2068    }
2069
2070    def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2071        """
2072        Set the FROM expression.
2073
2074        Example:
2075            >>> Select().from_("tbl").select("x").sql()
2076            'SELECT x FROM tbl'
2077
2078        Args:
2079            *expressions (str | Expression): the SQL code strings to parse.
2080                If a `From` instance is passed, this is used as-is.
2081                If another `Expression` instance is passed, it will be wrapped in a `From`.
2082            append (bool): if `True`, add to any existing expressions.
2083                Otherwise, this flattens all the `From` expression into a single expression.
2084            dialect (str): the dialect used to parse the input expression.
2085            copy (bool): if `False`, modify this expression instance in-place.
2086            opts (kwargs): other options to use to parse the input expressions.
2087
2088        Returns:
2089            Select: the modified expression.
2090        """
2091        return _apply_child_list_builder(
2092            *expressions,
2093            instance=self,
2094            arg="from",
2095            append=append,
2096            copy=copy,
2097            prefix="FROM",
2098            into=From,
2099            dialect=dialect,
2100            **opts,
2101        )
2102
2103    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2104        """
2105        Set the GROUP BY expression.
2106
2107        Example:
2108            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2109            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2110
2111        Args:
2112            *expressions (str | Expression): the SQL code strings to parse.
2113                If a `Group` instance is passed, this is used as-is.
2114                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2115                If nothing is passed in then a group by is not applied to the expression
2116            append (bool): if `True`, add to any existing expressions.
2117                Otherwise, this flattens all the `Group` expression into a single expression.
2118            dialect (str): the dialect used to parse the input expression.
2119            copy (bool): if `False`, modify this expression instance in-place.
2120            opts (kwargs): other options to use to parse the input expressions.
2121
2122        Returns:
2123            Select: the modified expression.
2124        """
2125        if not expressions:
2126            return self if not copy else self.copy()
2127        return _apply_child_list_builder(
2128            *expressions,
2129            instance=self,
2130            arg="group",
2131            append=append,
2132            copy=copy,
2133            prefix="GROUP BY",
2134            into=Group,
2135            dialect=dialect,
2136            **opts,
2137        )
2138
2139    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2140        """
2141        Set the ORDER BY expression.
2142
2143        Example:
2144            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2145            'SELECT x FROM tbl ORDER BY x DESC'
2146
2147        Args:
2148            *expressions (str | Expression): the SQL code strings to parse.
2149                If a `Group` instance is passed, this is used as-is.
2150                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2151            append (bool): if `True`, add to any existing expressions.
2152                Otherwise, this flattens all the `Order` expression into a single expression.
2153            dialect (str): the dialect used to parse the input expression.
2154            copy (bool): if `False`, modify this expression instance in-place.
2155            opts (kwargs): other options to use to parse the input expressions.
2156
2157        Returns:
2158            Select: the modified expression.
2159        """
2160        return _apply_child_list_builder(
2161            *expressions,
2162            instance=self,
2163            arg="order",
2164            append=append,
2165            copy=copy,
2166            prefix="ORDER BY",
2167            into=Order,
2168            dialect=dialect,
2169            **opts,
2170        )
2171
2172    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2173        """
2174        Set the SORT BY expression.
2175
2176        Example:
2177            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
2178            'SELECT x FROM tbl SORT BY x DESC'
2179
2180        Args:
2181            *expressions (str | Expression): the SQL code strings to parse.
2182                If a `Group` instance is passed, this is used as-is.
2183                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2184            append (bool): if `True`, add to any existing expressions.
2185                Otherwise, this flattens all the `Order` expression into a single expression.
2186            dialect (str): the dialect used to parse the input expression.
2187            copy (bool): if `False`, modify this expression instance in-place.
2188            opts (kwargs): other options to use to parse the input expressions.
2189
2190        Returns:
2191            Select: the modified expression.
2192        """
2193        return _apply_child_list_builder(
2194            *expressions,
2195            instance=self,
2196            arg="sort",
2197            append=append,
2198            copy=copy,
2199            prefix="SORT BY",
2200            into=Sort,
2201            dialect=dialect,
2202            **opts,
2203        )
2204
2205    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2206        """
2207        Set the CLUSTER BY expression.
2208
2209        Example:
2210            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
2211            'SELECT x FROM tbl CLUSTER BY x DESC'
2212
2213        Args:
2214            *expressions (str | Expression): the SQL code strings to parse.
2215                If a `Group` instance is passed, this is used as-is.
2216                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2217            append (bool): if `True`, add to any existing expressions.
2218                Otherwise, this flattens all the `Order` expression into a single expression.
2219            dialect (str): the dialect used to parse the input expression.
2220            copy (bool): if `False`, modify this expression instance in-place.
2221            opts (kwargs): other options to use to parse the input expressions.
2222
2223        Returns:
2224            Select: the modified expression.
2225        """
2226        return _apply_child_list_builder(
2227            *expressions,
2228            instance=self,
2229            arg="cluster",
2230            append=append,
2231            copy=copy,
2232            prefix="CLUSTER BY",
2233            into=Cluster,
2234            dialect=dialect,
2235            **opts,
2236        )
2237
2238    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2239        """
2240        Set the LIMIT expression.
2241
2242        Example:
2243            >>> Select().from_("tbl").select("x").limit(10).sql()
2244            'SELECT x FROM tbl LIMIT 10'
2245
2246        Args:
2247            expression (str | int | Expression): the SQL code string to parse.
2248                This can also be an integer.
2249                If a `Limit` instance is passed, this is used as-is.
2250                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2251            dialect (str): the dialect used to parse the input expression.
2252            copy (bool): if `False`, modify this expression instance in-place.
2253            opts (kwargs): other options to use to parse the input expressions.
2254
2255        Returns:
2256            Select: the modified expression.
2257        """
2258        return _apply_builder(
2259            expression=expression,
2260            instance=self,
2261            arg="limit",
2262            into=Limit,
2263            prefix="LIMIT",
2264            dialect=dialect,
2265            copy=copy,
2266            **opts,
2267        )
2268
2269    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2270        """
2271        Set the OFFSET expression.
2272
2273        Example:
2274            >>> Select().from_("tbl").select("x").offset(10).sql()
2275            'SELECT x FROM tbl OFFSET 10'
2276
2277        Args:
2278            expression (str | int | Expression): the SQL code string to parse.
2279                This can also be an integer.
2280                If a `Offset` instance is passed, this is used as-is.
2281                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2282            dialect (str): the dialect used to parse the input expression.
2283            copy (bool): if `False`, modify this expression instance in-place.
2284            opts (kwargs): other options to use to parse the input expressions.
2285
2286        Returns:
2287            Select: the modified expression.
2288        """
2289        return _apply_builder(
2290            expression=expression,
2291            instance=self,
2292            arg="offset",
2293            into=Offset,
2294            prefix="OFFSET",
2295            dialect=dialect,
2296            copy=copy,
2297            **opts,
2298        )
2299
2300    def select(
2301        self,
2302        *expressions: ExpOrStr,
2303        append: bool = True,
2304        dialect: DialectType = None,
2305        copy: bool = True,
2306        **opts,
2307    ) -> Select:
2308        """
2309        Append to or set the SELECT expressions.
2310
2311        Example:
2312            >>> Select().select("x", "y").sql()
2313            'SELECT x, y'
2314
2315        Args:
2316            *expressions: the SQL code strings to parse.
2317                If an `Expression` instance is passed, it will be used as-is.
2318            append: if `True`, add to any existing expressions.
2319                Otherwise, this resets the expressions.
2320            dialect: the dialect used to parse the input expressions.
2321            copy: if `False`, modify this expression instance in-place.
2322            opts: other options to use to parse the input expressions.
2323
2324        Returns:
2325            Select: the modified expression.
2326        """
2327        return _apply_list_builder(
2328            *expressions,
2329            instance=self,
2330            arg="expressions",
2331            append=append,
2332            dialect=dialect,
2333            copy=copy,
2334            **opts,
2335        )
2336
2337    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2338        """
2339        Append to or set the LATERAL expressions.
2340
2341        Example:
2342            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2343            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2344
2345        Args:
2346            *expressions (str | Expression): the SQL code strings to parse.
2347                If an `Expression` instance is passed, it will be used as-is.
2348            append (bool): if `True`, add to any existing expressions.
2349                Otherwise, this resets the expressions.
2350            dialect (str): the dialect used to parse the input expressions.
2351            copy (bool): if `False`, modify this expression instance in-place.
2352            opts (kwargs): other options to use to parse the input expressions.
2353
2354        Returns:
2355            Select: the modified expression.
2356        """
2357        return _apply_list_builder(
2358            *expressions,
2359            instance=self,
2360            arg="laterals",
2361            append=append,
2362            into=Lateral,
2363            prefix="LATERAL VIEW",
2364            dialect=dialect,
2365            copy=copy,
2366            **opts,
2367        )
2368
2369    def join(
2370        self,
2371        expression,
2372        on=None,
2373        using=None,
2374        append=True,
2375        join_type=None,
2376        join_alias=None,
2377        dialect=None,
2378        copy=True,
2379        **opts,
2380    ) -> Select:
2381        """
2382        Append to or set the JOIN expressions.
2383
2384        Example:
2385            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2386            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2387
2388            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2389            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2390
2391            Use `join_type` to change the type of join:
2392
2393            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2394            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2395
2396        Args:
2397            expression (str | Expression): the SQL code string to parse.
2398                If an `Expression` instance is passed, it will be used as-is.
2399            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2400                If an `Expression` instance is passed, it will be used as-is.
2401            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2402                If an `Expression` instance is passed, it will be used as-is.
2403            append (bool): if `True`, add to any existing expressions.
2404                Otherwise, this resets the expressions.
2405            join_type (str): If set, alter the parsed join type
2406            dialect (str): the dialect used to parse the input expressions.
2407            copy (bool): if `False`, modify this expression instance in-place.
2408            opts (kwargs): other options to use to parse the input expressions.
2409
2410        Returns:
2411            Select: the modified expression.
2412        """
2413        parse_args = {"dialect": dialect, **opts}
2414
2415        try:
2416            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2417        except ParseError:
2418            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2419
2420        join = expression if isinstance(expression, Join) else Join(this=expression)
2421
2422        if isinstance(join.this, Select):
2423            join.this.replace(join.this.subquery())
2424
2425        if join_type:
2426            natural: t.Optional[Token]
2427            side: t.Optional[Token]
2428            kind: t.Optional[Token]
2429
2430            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2431
2432            if natural:
2433                join.set("natural", True)
2434            if side:
2435                join.set("side", side.text)
2436            if kind:
2437                join.set("kind", kind.text)
2438
2439        if on:
2440            on = and_(*ensure_collection(on), dialect=dialect, **opts)
2441            join.set("on", on)
2442
2443        if using:
2444            join = _apply_list_builder(
2445                *ensure_collection(using),
2446                instance=join,
2447                arg="using",
2448                append=append,
2449                copy=copy,
2450                **opts,
2451            )
2452
2453        if join_alias:
2454            join.set("this", alias_(join.this, join_alias, table=True))
2455        return _apply_list_builder(
2456            join,
2457            instance=self,
2458            arg="joins",
2459            append=append,
2460            copy=copy,
2461            **opts,
2462        )
2463
2464    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2465        """
2466        Append to or set the WHERE expressions.
2467
2468        Example:
2469            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2470            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2471
2472        Args:
2473            *expressions (str | Expression): the SQL code strings to parse.
2474                If an `Expression` instance is passed, it will be used as-is.
2475                Multiple expressions are combined with an AND operator.
2476            append (bool): if `True`, AND the new expressions to any existing expression.
2477                Otherwise, this resets the expression.
2478            dialect (str): the dialect used to parse the input expressions.
2479            copy (bool): if `False`, modify this expression instance in-place.
2480            opts (kwargs): other options to use to parse the input expressions.
2481
2482        Returns:
2483            Select: the modified expression.
2484        """
2485        return _apply_conjunction_builder(
2486            *expressions,
2487            instance=self,
2488            arg="where",
2489            append=append,
2490            into=Where,
2491            dialect=dialect,
2492            copy=copy,
2493            **opts,
2494        )
2495
2496    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2497        """
2498        Append to or set the HAVING expressions.
2499
2500        Example:
2501            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2502            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2503
2504        Args:
2505            *expressions (str | Expression): the SQL code strings to parse.
2506                If an `Expression` instance is passed, it will be used as-is.
2507                Multiple expressions are combined with an AND operator.
2508            append (bool): if `True`, AND the new expressions to any existing expression.
2509                Otherwise, this resets the expression.
2510            dialect (str): the dialect used to parse the input expressions.
2511            copy (bool): if `False`, modify this expression instance in-place.
2512            opts (kwargs): other options to use to parse the input expressions.
2513
2514        Returns:
2515            Select: the modified expression.
2516        """
2517        return _apply_conjunction_builder(
2518            *expressions,
2519            instance=self,
2520            arg="having",
2521            append=append,
2522            into=Having,
2523            dialect=dialect,
2524            copy=copy,
2525            **opts,
2526        )
2527
2528    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2529        return _apply_list_builder(
2530            *expressions,
2531            instance=self,
2532            arg="windows",
2533            append=append,
2534            into=Window,
2535            dialect=dialect,
2536            copy=copy,
2537            **opts,
2538        )
2539
2540    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2541        return _apply_conjunction_builder(
2542            *expressions,
2543            instance=self,
2544            arg="qualify",
2545            append=append,
2546            into=Qualify,
2547            dialect=dialect,
2548            copy=copy,
2549            **opts,
2550        )
2551
2552    def distinct(self, distinct=True, copy=True) -> Select:
2553        """
2554        Set the OFFSET expression.
2555
2556        Example:
2557            >>> Select().from_("tbl").select("x").distinct().sql()
2558            'SELECT DISTINCT x FROM tbl'
2559
2560        Args:
2561            distinct (bool): whether the Select should be distinct
2562            copy (bool): if `False`, modify this expression instance in-place.
2563
2564        Returns:
2565            Select: the modified expression.
2566        """
2567        instance = _maybe_copy(self, copy)
2568        instance.set("distinct", Distinct() if distinct else None)
2569        return instance
2570
2571    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2572        """
2573        Convert this expression to a CREATE TABLE AS statement.
2574
2575        Example:
2576            >>> Select().select("*").from_("tbl").ctas("x").sql()
2577            'CREATE TABLE x AS SELECT * FROM tbl'
2578
2579        Args:
2580            table (str | Expression): the SQL code string to parse as the table name.
2581                If another `Expression` instance is passed, it will be used as-is.
2582            properties (dict): an optional mapping of table properties
2583            dialect (str): the dialect used to parse the input table.
2584            copy (bool): if `False`, modify this expression instance in-place.
2585            opts (kwargs): other options to use to parse the input table.
2586
2587        Returns:
2588            Create: the CREATE TABLE AS expression
2589        """
2590        instance = _maybe_copy(self, copy)
2591        table_expression = maybe_parse(
2592            table,
2593            into=Table,
2594            dialect=dialect,
2595            **opts,
2596        )
2597        properties_expression = None
2598        if properties:
2599            properties_expression = Properties.from_dict(properties)
2600
2601        return Create(
2602            this=table_expression,
2603            kind="table",
2604            expression=instance,
2605            properties=properties_expression,
2606        )
2607
2608    def lock(self, update: bool = True, copy: bool = True) -> Select:
2609        """
2610        Set the locking read mode for this expression.
2611
2612        Examples:
2613            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2614            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2615
2616            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2617            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2618
2619        Args:
2620            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2621            copy: if `False`, modify this expression instance in-place.
2622
2623        Returns:
2624            The modified expression.
2625        """
2626
2627        inst = _maybe_copy(self, copy)
2628        inst.set("lock", Lock(update=update))
2629
2630        return inst
2631
2632    @property
2633    def named_selects(self) -> t.List[str]:
2634        return [e.output_name for e in self.expressions if e.alias_or_name]
2635
2636    @property
2637    def is_star(self) -> bool:
2638        return any(expression.is_star for expression in self.expressions)
2639
2640    @property
2641    def selects(self) -> t.List[Expression]:
2642        return self.expressions
def from_( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2070    def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2071        """
2072        Set the FROM expression.
2073
2074        Example:
2075            >>> Select().from_("tbl").select("x").sql()
2076            'SELECT x FROM tbl'
2077
2078        Args:
2079            *expressions (str | Expression): the SQL code strings to parse.
2080                If a `From` instance is passed, this is used as-is.
2081                If another `Expression` instance is passed, it will be wrapped in a `From`.
2082            append (bool): if `True`, add to any existing expressions.
2083                Otherwise, this flattens all the `From` expression into a single expression.
2084            dialect (str): the dialect used to parse the input expression.
2085            copy (bool): if `False`, modify this expression instance in-place.
2086            opts (kwargs): other options to use to parse the input expressions.
2087
2088        Returns:
2089            Select: the modified expression.
2090        """
2091        return _apply_child_list_builder(
2092            *expressions,
2093            instance=self,
2094            arg="from",
2095            append=append,
2096            copy=copy,
2097            prefix="FROM",
2098            into=From,
2099            dialect=dialect,
2100            **opts,
2101        )

Set the FROM expression.

Example:
>>> Select().from_("tbl").select("x").sql()
'SELECT x FROM tbl'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a From instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a From.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the From expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def group_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2103    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2104        """
2105        Set the GROUP BY expression.
2106
2107        Example:
2108            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2109            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2110
2111        Args:
2112            *expressions (str | Expression): the SQL code strings to parse.
2113                If a `Group` instance is passed, this is used as-is.
2114                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2115                If nothing is passed in then a group by is not applied to the expression
2116            append (bool): if `True`, add to any existing expressions.
2117                Otherwise, this flattens all the `Group` expression into a single expression.
2118            dialect (str): the dialect used to parse the input expression.
2119            copy (bool): if `False`, modify this expression instance in-place.
2120            opts (kwargs): other options to use to parse the input expressions.
2121
2122        Returns:
2123            Select: the modified expression.
2124        """
2125        if not expressions:
2126            return self if not copy else self.copy()
2127        return _apply_child_list_builder(
2128            *expressions,
2129            instance=self,
2130            arg="group",
2131            append=append,
2132            copy=copy,
2133            prefix="GROUP BY",
2134            into=Group,
2135            dialect=dialect,
2136            **opts,
2137        )

Set the GROUP BY expression.

Example:
>>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
'SELECT x, COUNT(1) FROM tbl GROUP BY x'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Group. If nothing is passed in then a group by is not applied to the expression
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Group expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def order_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2139    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2140        """
2141        Set the ORDER BY expression.
2142
2143        Example:
2144            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2145            'SELECT x FROM tbl ORDER BY x DESC'
2146
2147        Args:
2148            *expressions (str | Expression): the SQL code strings to parse.
2149                If a `Group` instance is passed, this is used as-is.
2150                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2151            append (bool): if `True`, add to any existing expressions.
2152                Otherwise, this flattens all the `Order` expression into a single expression.
2153            dialect (str): the dialect used to parse the input expression.
2154            copy (bool): if `False`, modify this expression instance in-place.
2155            opts (kwargs): other options to use to parse the input expressions.
2156
2157        Returns:
2158            Select: the modified expression.
2159        """
2160        return _apply_child_list_builder(
2161            *expressions,
2162            instance=self,
2163            arg="order",
2164            append=append,
2165            copy=copy,
2166            prefix="ORDER BY",
2167            into=Order,
2168            dialect=dialect,
2169            **opts,
2170        )

Set the ORDER BY expression.

Example:
>>> Select().from_("tbl").select("x").order_by("x DESC").sql()
'SELECT x FROM tbl ORDER BY x DESC'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Order.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def sort_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2172    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2173        """
2174        Set the SORT BY expression.
2175
2176        Example:
2177            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
2178            'SELECT x FROM tbl SORT BY x DESC'
2179
2180        Args:
2181            *expressions (str | Expression): the SQL code strings to parse.
2182                If a `Group` instance is passed, this is used as-is.
2183                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2184            append (bool): if `True`, add to any existing expressions.
2185                Otherwise, this flattens all the `Order` expression into a single expression.
2186            dialect (str): the dialect used to parse the input expression.
2187            copy (bool): if `False`, modify this expression instance in-place.
2188            opts (kwargs): other options to use to parse the input expressions.
2189
2190        Returns:
2191            Select: the modified expression.
2192        """
2193        return _apply_child_list_builder(
2194            *expressions,
2195            instance=self,
2196            arg="sort",
2197            append=append,
2198            copy=copy,
2199            prefix="SORT BY",
2200            into=Sort,
2201            dialect=dialect,
2202            **opts,
2203        )

Set the SORT BY expression.

Example:
>>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
'SELECT x FROM tbl SORT BY x DESC'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a SORT.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def cluster_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2205    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2206        """
2207        Set the CLUSTER BY expression.
2208
2209        Example:
2210            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
2211            'SELECT x FROM tbl CLUSTER BY x DESC'
2212
2213        Args:
2214            *expressions (str | Expression): the SQL code strings to parse.
2215                If a `Group` instance is passed, this is used as-is.
2216                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2217            append (bool): if `True`, add to any existing expressions.
2218                Otherwise, this flattens all the `Order` expression into a single expression.
2219            dialect (str): the dialect used to parse the input expression.
2220            copy (bool): if `False`, modify this expression instance in-place.
2221            opts (kwargs): other options to use to parse the input expressions.
2222
2223        Returns:
2224            Select: the modified expression.
2225        """
2226        return _apply_child_list_builder(
2227            *expressions,
2228            instance=self,
2229            arg="cluster",
2230            append=append,
2231            copy=copy,
2232            prefix="CLUSTER BY",
2233            into=Cluster,
2234            dialect=dialect,
2235            **opts,
2236        )

Set the CLUSTER BY expression.

Example:
>>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
'SELECT x FROM tbl CLUSTER BY x DESC'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Cluster.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2238    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2239        """
2240        Set the LIMIT expression.
2241
2242        Example:
2243            >>> Select().from_("tbl").select("x").limit(10).sql()
2244            'SELECT x FROM tbl LIMIT 10'
2245
2246        Args:
2247            expression (str | int | Expression): the SQL code string to parse.
2248                This can also be an integer.
2249                If a `Limit` instance is passed, this is used as-is.
2250                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2251            dialect (str): the dialect used to parse the input expression.
2252            copy (bool): if `False`, modify this expression instance in-place.
2253            opts (kwargs): other options to use to parse the input expressions.
2254
2255        Returns:
2256            Select: the modified expression.
2257        """
2258        return _apply_builder(
2259            expression=expression,
2260            instance=self,
2261            arg="limit",
2262            into=Limit,
2263            prefix="LIMIT",
2264            dialect=dialect,
2265            copy=copy,
2266            **opts,
2267        )

Set the LIMIT expression.

Example:
>>> Select().from_("tbl").select("x").limit(10).sql()
'SELECT x FROM tbl LIMIT 10'
Arguments:
  • expression (str | int | Expression): the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def offset( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2269    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2270        """
2271        Set the OFFSET expression.
2272
2273        Example:
2274            >>> Select().from_("tbl").select("x").offset(10).sql()
2275            'SELECT x FROM tbl OFFSET 10'
2276
2277        Args:
2278            expression (str | int | Expression): the SQL code string to parse.
2279                This can also be an integer.
2280                If a `Offset` instance is passed, this is used as-is.
2281                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2282            dialect (str): the dialect used to parse the input expression.
2283            copy (bool): if `False`, modify this expression instance in-place.
2284            opts (kwargs): other options to use to parse the input expressions.
2285
2286        Returns:
2287            Select: the modified expression.
2288        """
2289        return _apply_builder(
2290            expression=expression,
2291            instance=self,
2292            arg="offset",
2293            into=Offset,
2294            prefix="OFFSET",
2295            dialect=dialect,
2296            copy=copy,
2297            **opts,
2298        )

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").offset(10).sql()
'SELECT x FROM tbl OFFSET 10'
Arguments:
  • expression (str | int | Expression): the SQL code string to parse. This can also be an integer. If a Offset instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Offset.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2300    def select(
2301        self,
2302        *expressions: ExpOrStr,
2303        append: bool = True,
2304        dialect: DialectType = None,
2305        copy: bool = True,
2306        **opts,
2307    ) -> Select:
2308        """
2309        Append to or set the SELECT expressions.
2310
2311        Example:
2312            >>> Select().select("x", "y").sql()
2313            'SELECT x, y'
2314
2315        Args:
2316            *expressions: the SQL code strings to parse.
2317                If an `Expression` instance is passed, it will be used as-is.
2318            append: if `True`, add to any existing expressions.
2319                Otherwise, this resets the expressions.
2320            dialect: the dialect used to parse the input expressions.
2321            copy: if `False`, modify this expression instance in-place.
2322            opts: other options to use to parse the input expressions.
2323
2324        Returns:
2325            Select: the modified expression.
2326        """
2327        return _apply_list_builder(
2328            *expressions,
2329            instance=self,
2330            arg="expressions",
2331            append=append,
2332            dialect=dialect,
2333            copy=copy,
2334            **opts,
2335        )

Append to or set the SELECT expressions.

Example:
>>> Select().select("x", "y").sql()
'SELECT x, y'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def lateral( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2337    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2338        """
2339        Append to or set the LATERAL expressions.
2340
2341        Example:
2342            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2343            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2344
2345        Args:
2346            *expressions (str | Expression): the SQL code strings to parse.
2347                If an `Expression` instance is passed, it will be used as-is.
2348            append (bool): if `True`, add to any existing expressions.
2349                Otherwise, this resets the expressions.
2350            dialect (str): the dialect used to parse the input expressions.
2351            copy (bool): if `False`, modify this expression instance in-place.
2352            opts (kwargs): other options to use to parse the input expressions.
2353
2354        Returns:
2355            Select: the modified expression.
2356        """
2357        return _apply_list_builder(
2358            *expressions,
2359            instance=self,
2360            arg="laterals",
2361            append=append,
2362            into=Lateral,
2363            prefix="LATERAL VIEW",
2364            dialect=dialect,
2365            copy=copy,
2366            **opts,
2367        )

Append to or set the LATERAL expressions.

Example:
>>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append (bool): if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def join( self, expression, on=None, using=None, append=True, join_type=None, join_alias=None, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2369    def join(
2370        self,
2371        expression,
2372        on=None,
2373        using=None,
2374        append=True,
2375        join_type=None,
2376        join_alias=None,
2377        dialect=None,
2378        copy=True,
2379        **opts,
2380    ) -> Select:
2381        """
2382        Append to or set the JOIN expressions.
2383
2384        Example:
2385            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2386            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2387
2388            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2389            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2390
2391            Use `join_type` to change the type of join:
2392
2393            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2394            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2395
2396        Args:
2397            expression (str | Expression): the SQL code string to parse.
2398                If an `Expression` instance is passed, it will be used as-is.
2399            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2400                If an `Expression` instance is passed, it will be used as-is.
2401            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2402                If an `Expression` instance is passed, it will be used as-is.
2403            append (bool): if `True`, add to any existing expressions.
2404                Otherwise, this resets the expressions.
2405            join_type (str): If set, alter the parsed join type
2406            dialect (str): the dialect used to parse the input expressions.
2407            copy (bool): if `False`, modify this expression instance in-place.
2408            opts (kwargs): other options to use to parse the input expressions.
2409
2410        Returns:
2411            Select: the modified expression.
2412        """
2413        parse_args = {"dialect": dialect, **opts}
2414
2415        try:
2416            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2417        except ParseError:
2418            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2419
2420        join = expression if isinstance(expression, Join) else Join(this=expression)
2421
2422        if isinstance(join.this, Select):
2423            join.this.replace(join.this.subquery())
2424
2425        if join_type:
2426            natural: t.Optional[Token]
2427            side: t.Optional[Token]
2428            kind: t.Optional[Token]
2429
2430            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2431
2432            if natural:
2433                join.set("natural", True)
2434            if side:
2435                join.set("side", side.text)
2436            if kind:
2437                join.set("kind", kind.text)
2438
2439        if on:
2440            on = and_(*ensure_collection(on), dialect=dialect, **opts)
2441            join.set("on", on)
2442
2443        if using:
2444            join = _apply_list_builder(
2445                *ensure_collection(using),
2446                instance=join,
2447                arg="using",
2448                append=append,
2449                copy=copy,
2450                **opts,
2451            )
2452
2453        if join_alias:
2454            join.set("this", alias_(join.this, join_alias, table=True))
2455        return _apply_list_builder(
2456            join,
2457            instance=self,
2458            arg="joins",
2459            append=append,
2460            copy=copy,
2461            **opts,
2462        )

Append to or set the JOIN expressions.

Example:
>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
>>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
'SELECT 1 FROM a JOIN b USING (x, y, z)'

Use join_type to change the type of join:

>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
Arguments:
  • expression (str | Expression): the SQL code string to parse. If an Expression instance is passed, it will be used as-is.
  • on (str | Expression): optionally specify the join "on" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • using (str | Expression): optionally specify the join "using" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • append (bool): if True, add to any existing expressions. Otherwise, this resets the expressions.
  • join_type (str): If set, alter the parsed join type
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def where( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2464    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2465        """
2466        Append to or set the WHERE expressions.
2467
2468        Example:
2469            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2470            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2471
2472        Args:
2473            *expressions (str | Expression): the SQL code strings to parse.
2474                If an `Expression` instance is passed, it will be used as-is.
2475                Multiple expressions are combined with an AND operator.
2476            append (bool): if `True`, AND the new expressions to any existing expression.
2477                Otherwise, this resets the expression.
2478            dialect (str): the dialect used to parse the input expressions.
2479            copy (bool): if `False`, modify this expression instance in-place.
2480            opts (kwargs): other options to use to parse the input expressions.
2481
2482        Returns:
2483            Select: the modified expression.
2484        """
2485        return _apply_conjunction_builder(
2486            *expressions,
2487            instance=self,
2488            arg="where",
2489            append=append,
2490            into=Where,
2491            dialect=dialect,
2492            copy=copy,
2493            **opts,
2494        )

Append to or set the WHERE expressions.

Example:
>>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
"SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append (bool): if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def having( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2496    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2497        """
2498        Append to or set the HAVING expressions.
2499
2500        Example:
2501            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2502            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2503
2504        Args:
2505            *expressions (str | Expression): the SQL code strings to parse.
2506                If an `Expression` instance is passed, it will be used as-is.
2507                Multiple expressions are combined with an AND operator.
2508            append (bool): if `True`, AND the new expressions to any existing expression.
2509                Otherwise, this resets the expression.
2510            dialect (str): the dialect used to parse the input expressions.
2511            copy (bool): if `False`, modify this expression instance in-place.
2512            opts (kwargs): other options to use to parse the input expressions.
2513
2514        Returns:
2515            Select: the modified expression.
2516        """
2517        return _apply_conjunction_builder(
2518            *expressions,
2519            instance=self,
2520            arg="having",
2521            append=append,
2522            into=Having,
2523            dialect=dialect,
2524            copy=copy,
2525            **opts,
2526        )

Append to or set the HAVING expressions.

Example:
>>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append (bool): if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def window( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2528    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2529        return _apply_list_builder(
2530            *expressions,
2531            instance=self,
2532            arg="windows",
2533            append=append,
2534            into=Window,
2535            dialect=dialect,
2536            copy=copy,
2537            **opts,
2538        )
def qualify( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2540    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2541        return _apply_conjunction_builder(
2542            *expressions,
2543            instance=self,
2544            arg="qualify",
2545            append=append,
2546            into=Qualify,
2547            dialect=dialect,
2548            copy=copy,
2549            **opts,
2550        )
def distinct(self, distinct=True, copy=True) -> sqlglot.expressions.Select:
2552    def distinct(self, distinct=True, copy=True) -> Select:
2553        """
2554        Set the OFFSET expression.
2555
2556        Example:
2557            >>> Select().from_("tbl").select("x").distinct().sql()
2558            'SELECT DISTINCT x FROM tbl'
2559
2560        Args:
2561            distinct (bool): whether the Select should be distinct
2562            copy (bool): if `False`, modify this expression instance in-place.
2563
2564        Returns:
2565            Select: the modified expression.
2566        """
2567        instance = _maybe_copy(self, copy)
2568        instance.set("distinct", Distinct() if distinct else None)
2569        return instance

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").distinct().sql()
'SELECT DISTINCT x FROM tbl'
Arguments:
  • distinct (bool): whether the Select should be distinct
  • copy (bool): if False, modify this expression instance in-place.
Returns:

Select: the modified expression.

def ctas( self, table, properties=None, dialect=None, copy=True, **opts) -> sqlglot.expressions.Create:
2571    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2572        """
2573        Convert this expression to a CREATE TABLE AS statement.
2574
2575        Example:
2576            >>> Select().select("*").from_("tbl").ctas("x").sql()
2577            'CREATE TABLE x AS SELECT * FROM tbl'
2578
2579        Args:
2580            table (str | Expression): the SQL code string to parse as the table name.
2581                If another `Expression` instance is passed, it will be used as-is.
2582            properties (dict): an optional mapping of table properties
2583            dialect (str): the dialect used to parse the input table.
2584            copy (bool): if `False`, modify this expression instance in-place.
2585            opts (kwargs): other options to use to parse the input table.
2586
2587        Returns:
2588            Create: the CREATE TABLE AS expression
2589        """
2590        instance = _maybe_copy(self, copy)
2591        table_expression = maybe_parse(
2592            table,
2593            into=Table,
2594            dialect=dialect,
2595            **opts,
2596        )
2597        properties_expression = None
2598        if properties:
2599            properties_expression = Properties.from_dict(properties)
2600
2601        return Create(
2602            this=table_expression,
2603            kind="table",
2604            expression=instance,
2605            properties=properties_expression,
2606        )

Convert this expression to a CREATE TABLE AS statement.

Example:
>>> Select().select("*").from_("tbl").ctas("x").sql()
'CREATE TABLE x AS SELECT * FROM tbl'
Arguments:
  • table (str | Expression): the SQL code string to parse as the table name. If another Expression instance is passed, it will be used as-is.
  • properties (dict): an optional mapping of table properties
  • dialect (str): the dialect used to parse the input table.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input table.
Returns:

Create: the CREATE TABLE AS expression

def lock( self, update: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
2608    def lock(self, update: bool = True, copy: bool = True) -> Select:
2609        """
2610        Set the locking read mode for this expression.
2611
2612        Examples:
2613            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2614            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2615
2616            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2617            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2618
2619        Args:
2620            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2621            copy: if `False`, modify this expression instance in-place.
2622
2623        Returns:
2624            The modified expression.
2625        """
2626
2627        inst = _maybe_copy(self, copy)
2628        inst.set("lock", Lock(update=update))
2629
2630        return inst

Set the locking read mode for this expression.

Examples:
>>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
>>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
Arguments:
  • update: if True, the locking type will be FOR UPDATE, else it will be FOR SHARE.
  • copy: if False, modify this expression instance in-place.
Returns:

The modified expression.

is_star: bool

Checks whether an expression is a star.

class Subquery(DerivedTable, Unionable):
2645class Subquery(DerivedTable, Unionable):
2646    arg_types = {
2647        "this": True,
2648        "alias": False,
2649        "with": False,
2650        **QUERY_MODIFIERS,
2651    }
2652
2653    def unnest(self):
2654        """
2655        Returns the first non subquery.
2656        """
2657        expression = self
2658        while isinstance(expression, Subquery):
2659            expression = expression.this
2660        return expression
2661
2662    @property
2663    def is_star(self) -> bool:
2664        return self.this.is_star
2665
2666    @property
2667    def output_name(self):
2668        return self.alias
def unnest(self):
2653    def unnest(self):
2654        """
2655        Returns the first non subquery.
2656        """
2657        expression = self
2658        while isinstance(expression, Subquery):
2659            expression = expression.this
2660        return expression

Returns the first non subquery.

is_star: bool

Checks whether an expression is a star.

output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class TableSample(Expression):
2671class TableSample(Expression):
2672    arg_types = {
2673        "this": False,
2674        "method": False,
2675        "bucket_numerator": False,
2676        "bucket_denominator": False,
2677        "bucket_field": False,
2678        "percent": False,
2679        "rows": False,
2680        "size": False,
2681        "seed": False,
2682        "kind": False,
2683    }
class Tag(Expression):
2686class Tag(Expression):
2687    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
2688
2689    arg_types = {
2690        "this": False,
2691        "prefix": False,
2692        "postfix": False,
2693    }

Tags are used for generating arbitrary sql like SELECT x.

class Pivot(Expression):
2696class Pivot(Expression):
2697    arg_types = {
2698        "this": False,
2699        "alias": False,
2700        "expressions": True,
2701        "field": True,
2702        "unpivot": True,
2703    }
class Window(Expression):
2706class Window(Expression):
2707    arg_types = {
2708        "this": True,
2709        "partition_by": False,
2710        "order": False,
2711        "spec": False,
2712        "alias": False,
2713    }
class WindowSpec(Expression):
2716class WindowSpec(Expression):
2717    arg_types = {
2718        "kind": False,
2719        "start": False,
2720        "start_side": False,
2721        "end": False,
2722        "end_side": False,
2723    }
class Where(Expression):
2726class Where(Expression):
2727    pass
class Star(Expression):
2730class Star(Expression):
2731    arg_types = {"except": False, "replace": False}
2732
2733    @property
2734    def name(self) -> str:
2735        return "*"
2736
2737    @property
2738    def output_name(self):
2739        return self.name
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Parameter(Expression):
2742class Parameter(Expression):
2743    arg_types = {"this": True, "wrapped": False}
class SessionParameter(Expression):
2746class SessionParameter(Expression):
2747    arg_types = {"this": True, "kind": False}
class Placeholder(Expression):
2750class Placeholder(Expression):
2751    arg_types = {"this": False}
class Null(Condition):
2754class Null(Condition):
2755    arg_types: t.Dict[str, t.Any] = {}
2756
2757    @property
2758    def name(self) -> str:
2759        return "NULL"
class Boolean(Condition):
2762class Boolean(Condition):
2763    pass
class DataType(Expression):
2766class DataType(Expression):
2767    arg_types = {
2768        "this": True,
2769        "expressions": False,
2770        "nested": False,
2771        "values": False,
2772        "prefix": False,
2773    }
2774
2775    class Type(AutoName):
2776        CHAR = auto()
2777        NCHAR = auto()
2778        VARCHAR = auto()
2779        NVARCHAR = auto()
2780        TEXT = auto()
2781        MEDIUMTEXT = auto()
2782        LONGTEXT = auto()
2783        MEDIUMBLOB = auto()
2784        LONGBLOB = auto()
2785        BINARY = auto()
2786        VARBINARY = auto()
2787        INT = auto()
2788        UINT = auto()
2789        TINYINT = auto()
2790        UTINYINT = auto()
2791        SMALLINT = auto()
2792        USMALLINT = auto()
2793        BIGINT = auto()
2794        UBIGINT = auto()
2795        FLOAT = auto()
2796        DOUBLE = auto()
2797        DECIMAL = auto()
2798        BIT = auto()
2799        BOOLEAN = auto()
2800        JSON = auto()
2801        JSONB = auto()
2802        INTERVAL = auto()
2803        TIME = auto()
2804        TIMESTAMP = auto()
2805        TIMESTAMPTZ = auto()
2806        TIMESTAMPLTZ = auto()
2807        DATE = auto()
2808        DATETIME = auto()
2809        ARRAY = auto()
2810        MAP = auto()
2811        UUID = auto()
2812        GEOGRAPHY = auto()
2813        GEOMETRY = auto()
2814        STRUCT = auto()
2815        NULLABLE = auto()
2816        HLLSKETCH = auto()
2817        HSTORE = auto()
2818        SUPER = auto()
2819        SERIAL = auto()
2820        SMALLSERIAL = auto()
2821        BIGSERIAL = auto()
2822        XML = auto()
2823        UNIQUEIDENTIFIER = auto()
2824        MONEY = auto()
2825        SMALLMONEY = auto()
2826        ROWVERSION = auto()
2827        IMAGE = auto()
2828        VARIANT = auto()
2829        OBJECT = auto()
2830        INET = auto()
2831        NULL = auto()
2832        UNKNOWN = auto()  # Sentinel value, useful for type annotation
2833
2834    TEXT_TYPES = {
2835        Type.CHAR,
2836        Type.NCHAR,
2837        Type.VARCHAR,
2838        Type.NVARCHAR,
2839        Type.TEXT,
2840    }
2841
2842    INTEGER_TYPES = {
2843        Type.INT,
2844        Type.TINYINT,
2845        Type.SMALLINT,
2846        Type.BIGINT,
2847    }
2848
2849    FLOAT_TYPES = {
2850        Type.FLOAT,
2851        Type.DOUBLE,
2852    }
2853
2854    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
2855
2856    TEMPORAL_TYPES = {
2857        Type.TIMESTAMP,
2858        Type.TIMESTAMPTZ,
2859        Type.TIMESTAMPLTZ,
2860        Type.DATE,
2861        Type.DATETIME,
2862    }
2863
2864    @classmethod
2865    def build(
2866        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
2867    ) -> DataType:
2868        from sqlglot import parse_one
2869
2870        if isinstance(dtype, str):
2871            if dtype.upper() in cls.Type.__members__:
2872                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
2873            else:
2874                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
2875            if data_type_exp is None:
2876                raise ValueError(f"Unparsable data type value: {dtype}")
2877        elif isinstance(dtype, DataType.Type):
2878            data_type_exp = DataType(this=dtype)
2879        elif isinstance(dtype, DataType):
2880            return dtype
2881        else:
2882            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
2883        return DataType(**{**data_type_exp.args, **kwargs})
2884
2885    def is_type(self, dtype: DataType.Type) -> bool:
2886        return self.this == dtype
@classmethod
def build( cls, dtype: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.DataType:
2864    @classmethod
2865    def build(
2866        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
2867    ) -> DataType:
2868        from sqlglot import parse_one
2869
2870        if isinstance(dtype, str):
2871            if dtype.upper() in cls.Type.__members__:
2872                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
2873            else:
2874                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
2875            if data_type_exp is None:
2876                raise ValueError(f"Unparsable data type value: {dtype}")
2877        elif isinstance(dtype, DataType.Type):
2878            data_type_exp = DataType(this=dtype)
2879        elif isinstance(dtype, DataType):
2880            return dtype
2881        else:
2882            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
2883        return DataType(**{**data_type_exp.args, **kwargs})
def is_type(self, dtype: sqlglot.expressions.DataType.Type) -> bool:
2885    def is_type(self, dtype: DataType.Type) -> bool:
2886        return self.this == dtype
class DataType.Type(sqlglot.helper.AutoName):
2775    class Type(AutoName):
2776        CHAR = auto()
2777        NCHAR = auto()
2778        VARCHAR = auto()
2779        NVARCHAR = auto()
2780        TEXT = auto()
2781        MEDIUMTEXT = auto()
2782        LONGTEXT = auto()
2783        MEDIUMBLOB = auto()
2784        LONGBLOB = auto()
2785        BINARY = auto()
2786        VARBINARY = auto()
2787        INT = auto()
2788        UINT = auto()
2789        TINYINT = auto()
2790        UTINYINT = auto()
2791        SMALLINT = auto()
2792        USMALLINT = auto()
2793        BIGINT = auto()
2794        UBIGINT = auto()
2795        FLOAT = auto()
2796        DOUBLE = auto()
2797        DECIMAL = auto()
2798        BIT = auto()
2799        BOOLEAN = auto()
2800        JSON = auto()
2801        JSONB = auto()
2802        INTERVAL = auto()
2803        TIME = auto()
2804        TIMESTAMP = auto()
2805        TIMESTAMPTZ = auto()
2806        TIMESTAMPLTZ = auto()
2807        DATE = auto()
2808        DATETIME = auto()
2809        ARRAY = auto()
2810        MAP = auto()
2811        UUID = auto()
2812        GEOGRAPHY = auto()
2813        GEOMETRY = auto()
2814        STRUCT = auto()
2815        NULLABLE = auto()
2816        HLLSKETCH = auto()
2817        HSTORE = auto()
2818        SUPER = auto()
2819        SERIAL = auto()
2820        SMALLSERIAL = auto()
2821        BIGSERIAL = auto()
2822        XML = auto()
2823        UNIQUEIDENTIFIER = auto()
2824        MONEY = auto()
2825        SMALLMONEY = auto()
2826        ROWVERSION = auto()
2827        IMAGE = auto()
2828        VARIANT = auto()
2829        OBJECT = auto()
2830        INET = auto()
2831        NULL = auto()
2832        UNKNOWN = auto()  # Sentinel value, useful for type annotation

An enumeration.

CHAR = <Type.CHAR: 'CHAR'>
NCHAR = <Type.NCHAR: 'NCHAR'>
VARCHAR = <Type.VARCHAR: 'VARCHAR'>
NVARCHAR = <Type.NVARCHAR: 'NVARCHAR'>
TEXT = <Type.TEXT: 'TEXT'>
MEDIUMTEXT = <Type.MEDIUMTEXT: 'MEDIUMTEXT'>
LONGTEXT = <Type.LONGTEXT: 'LONGTEXT'>
MEDIUMBLOB = <Type.MEDIUMBLOB: 'MEDIUMBLOB'>
LONGBLOB = <Type.LONGBLOB: 'LONGBLOB'>
BINARY = <Type.BINARY: 'BINARY'>
VARBINARY = <Type.VARBINARY: 'VARBINARY'>
INT = <Type.INT: 'INT'>
UINT = <Type.UINT: 'UINT'>
TINYINT = <Type.TINYINT: 'TINYINT'>
UTINYINT = <Type.UTINYINT: 'UTINYINT'>
SMALLINT = <Type.SMALLINT: 'SMALLINT'>
USMALLINT = <Type.USMALLINT: 'USMALLINT'>
BIGINT = <Type.BIGINT: 'BIGINT'>
UBIGINT = <Type.UBIGINT: 'UBIGINT'>
FLOAT = <Type.FLOAT: 'FLOAT'>
DOUBLE = <Type.DOUBLE: 'DOUBLE'>
DECIMAL = <Type.DECIMAL: 'DECIMAL'>
BIT = <Type.BIT: 'BIT'>
BOOLEAN = <Type.BOOLEAN: 'BOOLEAN'>
JSON = <Type.JSON: 'JSON'>
JSONB = <Type.JSONB: 'JSONB'>
INTERVAL = <Type.INTERVAL: 'INTERVAL'>
TIME = <Type.TIME: 'TIME'>
TIMESTAMP = <Type.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPTZ = <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TIMESTAMPLTZ = <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
DATE = <Type.DATE: 'DATE'>
DATETIME = <Type.DATETIME: 'DATETIME'>
ARRAY = <Type.ARRAY: 'ARRAY'>
MAP = <Type.MAP: 'MAP'>
UUID = <Type.UUID: 'UUID'>
GEOGRAPHY = <Type.GEOGRAPHY: 'GEOGRAPHY'>
GEOMETRY = <Type.GEOMETRY: 'GEOMETRY'>
STRUCT = <Type.STRUCT: 'STRUCT'>
NULLABLE = <Type.NULLABLE: 'NULLABLE'>
HLLSKETCH = <Type.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <Type.HSTORE: 'HSTORE'>
SUPER = <Type.SUPER: 'SUPER'>
SERIAL = <Type.SERIAL: 'SERIAL'>
SMALLSERIAL = <Type.SMALLSERIAL: 'SMALLSERIAL'>
BIGSERIAL = <Type.BIGSERIAL: 'BIGSERIAL'>
XML = <Type.XML: 'XML'>
UNIQUEIDENTIFIER = <Type.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
MONEY = <Type.MONEY: 'MONEY'>
SMALLMONEY = <Type.SMALLMONEY: 'SMALLMONEY'>
ROWVERSION = <Type.ROWVERSION: 'ROWVERSION'>
IMAGE = <Type.IMAGE: 'IMAGE'>
VARIANT = <Type.VARIANT: 'VARIANT'>
OBJECT = <Type.OBJECT: 'OBJECT'>
INET = <Type.INET: 'INET'>
NULL = <Type.NULL: 'NULL'>
UNKNOWN = <Type.UNKNOWN: 'UNKNOWN'>
Inherited Members
enum.Enum
name
value
class PseudoType(Expression):
2890class PseudoType(Expression):
2891    pass
class StructKwarg(Expression):
2894class StructKwarg(Expression):
2895    arg_types = {"this": True, "expression": True}
class SubqueryPredicate(Predicate):
2899class SubqueryPredicate(Predicate):
2900    pass
class All(SubqueryPredicate):
2903class All(SubqueryPredicate):
2904    pass
class Any(SubqueryPredicate):
2907class Any(SubqueryPredicate):
2908    pass
class Exists(SubqueryPredicate):
2911class Exists(SubqueryPredicate):
2912    pass
class Command(Expression):
2917class Command(Expression):
2918    arg_types = {"this": True, "expression": False}
class Transaction(Expression):
2921class Transaction(Expression):
2922    arg_types = {"this": False, "modes": False}
class Commit(Expression):
2925class Commit(Expression):
2926    arg_types = {"chain": False}
class Rollback(Expression):
2929class Rollback(Expression):
2930    arg_types = {"savepoint": False}
class AlterTable(Expression):
2933class AlterTable(Expression):
2934    arg_types = {"this": True, "actions": True, "exists": False}
class AddConstraint(Expression):
2937class AddConstraint(Expression):
2938    arg_types = {"this": False, "expression": False, "enforced": False}
class DropPartition(Expression):
2941class DropPartition(Expression):
2942    arg_types = {"expressions": True, "exists": False}
class Binary(Expression):
2946class Binary(Expression):
2947    arg_types = {"this": True, "expression": True}
2948
2949    @property
2950    def left(self):
2951        return self.this
2952
2953    @property
2954    def right(self):
2955        return self.expression
class Add(Binary):
2958class Add(Binary):
2959    pass
class Connector(Binary, Condition):
2962class Connector(Binary, Condition):
2963    pass
class And(Connector):
2966class And(Connector):
2967    pass
class Or(Connector):
2970class Or(Connector):
2971    pass
class BitwiseAnd(Binary):
2974class BitwiseAnd(Binary):
2975    pass
class BitwiseLeftShift(Binary):
2978class BitwiseLeftShift(Binary):
2979    pass
class BitwiseOr(Binary):
2982class BitwiseOr(Binary):
2983    pass
class BitwiseRightShift(Binary):
2986class BitwiseRightShift(Binary):
2987    pass
class BitwiseXor(Binary):
2990class BitwiseXor(Binary):
2991    pass
class Div(Binary):
2994class Div(Binary):
2995    pass
class Overlaps(Binary):
2998class Overlaps(Binary):
2999    pass
class Dot(Binary):
3002class Dot(Binary):
3003    @property
3004    def name(self) -> str:
3005        return self.expression.name
3006
3007    @classmethod
3008    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3009        """Build a Dot object with a sequence of expressions."""
3010        if len(expressions) < 2:
3011            raise ValueError(f"Dot requires >= 2 expressions.")
3012
3013        a, b, *expressions = expressions
3014        dot = Dot(this=a, expression=b)
3015
3016        for expression in expressions:
3017            dot = Dot(this=dot, expression=expression)
3018
3019        return dot
@classmethod
def build( self, expressions: Sequence[sqlglot.expressions.Expression]) -> sqlglot.expressions.Dot:
3007    @classmethod
3008    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3009        """Build a Dot object with a sequence of expressions."""
3010        if len(expressions) < 2:
3011            raise ValueError(f"Dot requires >= 2 expressions.")
3012
3013        a, b, *expressions = expressions
3014        dot = Dot(this=a, expression=b)
3015
3016        for expression in expressions:
3017            dot = Dot(this=dot, expression=expression)
3018
3019        return dot

Build a Dot object with a sequence of expressions.

class DPipe(Binary):
3022class DPipe(Binary):
3023    pass
class EQ(Binary, Predicate):
3026class EQ(Binary, Predicate):
3027    pass
class NullSafeEQ(Binary, Predicate):
3030class NullSafeEQ(Binary, Predicate):
3031    pass
class NullSafeNEQ(Binary, Predicate):
3034class NullSafeNEQ(Binary, Predicate):
3035    pass
class Distance(Binary):
3038class Distance(Binary):
3039    pass
class Escape(Binary):
3042class Escape(Binary):
3043    pass
class Glob(Binary, Predicate):
3046class Glob(Binary, Predicate):
3047    pass
class GT(Binary, Predicate):
3050class GT(Binary, Predicate):
3051    pass
class GTE(Binary, Predicate):
3054class GTE(Binary, Predicate):
3055    pass
class ILike(Binary, Predicate):
3058class ILike(Binary, Predicate):
3059    pass
class ILikeAny(Binary, Predicate):
3062class ILikeAny(Binary, Predicate):
3063    pass
class IntDiv(Binary):
3066class IntDiv(Binary):
3067    pass
class Is(Binary, Predicate):
3070class Is(Binary, Predicate):
3071    pass
class Kwarg(Binary):
3074class Kwarg(Binary):
3075    """Kwarg in special functions like func(kwarg => y)."""

Kwarg in special functions like func(kwarg => y).

class Like(Binary, Predicate):
3078class Like(Binary, Predicate):
3079    pass
class LikeAny(Binary, Predicate):
3082class LikeAny(Binary, Predicate):
3083    pass
class LT(Binary, Predicate):
3086class LT(Binary, Predicate):
3087    pass
class LTE(Binary, Predicate):
3090class LTE(Binary, Predicate):
3091    pass
class Mod(Binary):
3094class Mod(Binary):
3095    pass
class Mul(Binary):
3098class Mul(Binary):
3099    pass
class NEQ(Binary, Predicate):
3102class NEQ(Binary, Predicate):
3103    pass
class SimilarTo(Binary, Predicate):
3106class SimilarTo(Binary, Predicate):
3107    pass
class Slice(Binary):
3110class Slice(Binary):
3111    arg_types = {"this": False, "expression": False}
class Sub(Binary):
3114class Sub(Binary):
3115    pass
class ArrayOverlaps(Binary):
3118class ArrayOverlaps(Binary):
3119    pass
class Unary(Expression):
3124class Unary(Expression):
3125    pass
class BitwiseNot(Unary):
3128class BitwiseNot(Unary):
3129    pass
class Not(Unary, Condition):
3132class Not(Unary, Condition):
3133    pass
class Paren(Unary, Condition):
3136class Paren(Unary, Condition):
3137    arg_types = {"this": True, "with": False}
class Neg(Unary):
3140class Neg(Unary):
3141    pass
class Alias(Expression):
3145class Alias(Expression):
3146    arg_types = {"this": True, "alias": False}
3147
3148    @property
3149    def output_name(self):
3150        return self.alias
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Aliases(Expression):
3153class Aliases(Expression):
3154    arg_types = {"this": True, "expressions": True}
3155
3156    @property
3157    def aliases(self):
3158        return self.expressions
class AtTimeZone(Expression):
3161class AtTimeZone(Expression):
3162    arg_types = {"this": True, "zone": True}
class Between(Predicate):
3165class Between(Predicate):
3166    arg_types = {"this": True, "low": True, "high": True}
class Bracket(Condition):
3169class Bracket(Condition):
3170    arg_types = {"this": True, "expressions": True}
class Distinct(Expression):
3173class Distinct(Expression):
3174    arg_types = {"expressions": False, "on": False}
class In(Predicate):
3177class In(Predicate):
3178    arg_types = {
3179        "this": True,
3180        "expressions": False,
3181        "query": False,
3182        "unnest": False,
3183        "field": False,
3184        "is_global": False,
3185    }
class TimeUnit(Expression):
3188class TimeUnit(Expression):
3189    """Automatically converts unit arg into a var."""
3190
3191    arg_types = {"unit": False}
3192
3193    def __init__(self, **args):
3194        unit = args.get("unit")
3195        if isinstance(unit, (Column, Literal)):
3196            args["unit"] = Var(this=unit.name)
3197        elif isinstance(unit, Week):
3198            unit.set("this", Var(this=unit.this.name))
3199        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3193    def __init__(self, **args):
3194        unit = args.get("unit")
3195        if isinstance(unit, (Column, Literal)):
3196            args["unit"] = Var(this=unit.name)
3197        elif isinstance(unit, Week):
3198            unit.set("this", Var(this=unit.this.name))
3199        super().__init__(**args)
class Interval(TimeUnit):
3202class Interval(TimeUnit):
3203    arg_types = {"this": False, "unit": False}
class IgnoreNulls(Expression):
3206class IgnoreNulls(Expression):
3207    pass
class RespectNulls(Expression):
3210class RespectNulls(Expression):
3211    pass
class Func(Condition):
3215class Func(Condition):
3216    """
3217    The base class for all function expressions.
3218
3219    Attributes:
3220        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3221            treated as a variable length argument and the argument's value will be stored as a list.
3222        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3223            for this function expression. These values are used to map this node to a name during parsing
3224            as well as to provide the function's name during SQL string generation. By default the SQL
3225            name is set to the expression's class name transformed to snake case.
3226    """
3227
3228    is_var_len_args = False
3229
3230    @classmethod
3231    def from_arg_list(cls, args):
3232        if cls.is_var_len_args:
3233            all_arg_keys = list(cls.arg_types)
3234            # If this function supports variable length argument treat the last argument as such.
3235            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3236            num_non_var = len(non_var_len_arg_keys)
3237
3238            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3239            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3240        else:
3241            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3242
3243        return cls(**args_dict)
3244
3245    @classmethod
3246    def sql_names(cls):
3247        if cls is Func:
3248            raise NotImplementedError(
3249                "SQL name is only supported by concrete function implementations"
3250            )
3251        if "_sql_names" not in cls.__dict__:
3252            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3253        return cls._sql_names
3254
3255    @classmethod
3256    def sql_name(cls):
3257        return cls.sql_names()[0]
3258
3259    @classmethod
3260    def default_parser_mappings(cls):
3261        return {name: cls.from_arg_list for name in cls.sql_names()}

The base class for all function expressions.

Attributes:
  • is_var_len_args (bool): if set to True the last argument defined in arg_types will be treated as a variable length argument and the argument's value will be stored as a list.
  • _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) for this function expression. These values are used to map this node to a name during parsing as well as to provide the function's name during SQL string generation. By default the SQL name is set to the expression's class name transformed to snake case.
@classmethod
def from_arg_list(cls, args):
3230    @classmethod
3231    def from_arg_list(cls, args):
3232        if cls.is_var_len_args:
3233            all_arg_keys = list(cls.arg_types)
3234            # If this function supports variable length argument treat the last argument as such.
3235            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3236            num_non_var = len(non_var_len_arg_keys)
3237
3238            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3239            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3240        else:
3241            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3242
3243        return cls(**args_dict)
@classmethod
def sql_names(cls):
3245    @classmethod
3246    def sql_names(cls):
3247        if cls is Func:
3248            raise NotImplementedError(
3249                "SQL name is only supported by concrete function implementations"
3250            )
3251        if "_sql_names" not in cls.__dict__:
3252            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3253        return cls._sql_names
@classmethod
def sql_name(cls):
3255    @classmethod
3256    def sql_name(cls):
3257        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3259    @classmethod
3260    def default_parser_mappings(cls):
3261        return {name: cls.from_arg_list for name in cls.sql_names()}
class AggFunc(Func):
3264class AggFunc(Func):
3265    pass
class Abs(Func):
3268class Abs(Func):
3269    pass
class Anonymous(Func):
3272class Anonymous(Func):
3273    arg_types = {"this": True, "expressions": False}
3274    is_var_len_args = True
class ApproxDistinct(AggFunc):
3277class ApproxDistinct(AggFunc):
3278    arg_types = {"this": True, "accuracy": False}
class Array(Func):
3281class Array(Func):
3282    arg_types = {"expressions": False}
3283    is_var_len_args = True
class ToChar(Func):
3287class ToChar(Func):
3288    arg_types = {"this": True, "format": False}
class GenerateSeries(Func):
3291class GenerateSeries(Func):
3292    arg_types = {"start": True, "end": True, "step": False}
class ArrayAgg(AggFunc):
3295class ArrayAgg(AggFunc):
3296    pass
class ArrayAll(Func):
3299class ArrayAll(Func):
3300    arg_types = {"this": True, "expression": True}
class ArrayAny(Func):
3303class ArrayAny(Func):
3304    arg_types = {"this": True, "expression": True}
class ArrayConcat(Func):
3307class ArrayConcat(Func):
3308    arg_types = {"this": True, "expressions": False}
3309    is_var_len_args = True
class ArrayContains(Binary, Func):
3312class ArrayContains(Binary, Func):
3313    pass
class ArrayContained(Binary):
3316class ArrayContained(Binary):
3317    pass
class ArrayFilter(Func):
3320class ArrayFilter(Func):
3321    arg_types = {"this": True, "expression": True}
3322    _sql_names = ["FILTER", "ARRAY_FILTER"]
class ArrayJoin(Func):
3325class ArrayJoin(Func):
3326    arg_types = {"this": True, "expression": True, "null": False}
class ArraySize(Func):
3329class ArraySize(Func):
3330    arg_types = {"this": True, "expression": False}
class ArraySort(Func):
3333class ArraySort(Func):
3334    arg_types = {"this": True, "expression": False}
class ArraySum(Func):
3337class ArraySum(Func):
3338    pass
class ArrayUnionAgg(AggFunc):
3341class ArrayUnionAgg(AggFunc):
3342    pass
class Avg(AggFunc):
3345class Avg(AggFunc):
3346    pass
class AnyValue(AggFunc):
3349class AnyValue(AggFunc):
3350    pass
class Case(Func):
3353class Case(Func):
3354    arg_types = {"this": False, "ifs": True, "default": False}
class Cast(Func):
3357class Cast(Func):
3358    arg_types = {"this": True, "to": True}
3359
3360    @property
3361    def name(self) -> str:
3362        return self.this.name
3363
3364    @property
3365    def to(self):
3366        return self.args["to"]
3367
3368    @property
3369    def output_name(self):
3370        return self.name
3371
3372    def is_type(self, dtype: DataType.Type) -> bool:
3373        return self.to.is_type(dtype)
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
def is_type(self, dtype: sqlglot.expressions.DataType.Type) -> bool:
3372    def is_type(self, dtype: DataType.Type) -> bool:
3373        return self.to.is_type(dtype)
class Collate(Binary):
3376class Collate(Binary):
3377    pass
class TryCast(Cast):
3380class TryCast(Cast):
3381    pass
class Ceil(Func):
3384class Ceil(Func):
3385    arg_types = {"this": True, "decimals": False}
3386    _sql_names = ["CEIL", "CEILING"]
class Coalesce(Func):
3389class Coalesce(Func):
3390    arg_types = {"this": True, "expressions": False}
3391    is_var_len_args = True
class Concat(Func):
3394class Concat(Func):
3395    arg_types = {"expressions": True}
3396    is_var_len_args = True
class ConcatWs(Concat):
3399class ConcatWs(Concat):
3400    _sql_names = ["CONCAT_WS"]
class Count(AggFunc):
3403class Count(AggFunc):
3404    arg_types = {"this": False}
class CountIf(AggFunc):
3407class CountIf(AggFunc):
3408    pass
class CurrentDate(Func):
3411class CurrentDate(Func):
3412    arg_types = {"this": False}
class CurrentDatetime(Func):
3415class CurrentDatetime(Func):
3416    arg_types = {"this": False}
class CurrentTime(Func):
3419class CurrentTime(Func):
3420    arg_types = {"this": False}
class CurrentTimestamp(Func):
3423class CurrentTimestamp(Func):
3424    arg_types = {"this": False}
class DateAdd(Func, TimeUnit):
3427class DateAdd(Func, TimeUnit):
3428    arg_types = {"this": True, "expression": True, "unit": False}
class DateSub(Func, TimeUnit):
3431class DateSub(Func, TimeUnit):
3432    arg_types = {"this": True, "expression": True, "unit": False}
class DateDiff(Func, TimeUnit):
3435class DateDiff(Func, TimeUnit):
3436    _sql_names = ["DATEDIFF", "DATE_DIFF"]
3437    arg_types = {"this": True, "expression": True, "unit": False}
class DateTrunc(Func):
3440class DateTrunc(Func):
3441    arg_types = {"unit": True, "this": True, "zone": False}
class DatetimeAdd(Func, TimeUnit):
3444class DatetimeAdd(Func, TimeUnit):
3445    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeSub(Func, TimeUnit):
3448class DatetimeSub(Func, TimeUnit):
3449    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeDiff(Func, TimeUnit):
3452class DatetimeDiff(Func, TimeUnit):
3453    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeTrunc(Func, TimeUnit):
3456class DatetimeTrunc(Func, TimeUnit):
3457    arg_types = {"this": True, "unit": True, "zone": False}
class DayOfWeek(Func):
3460class DayOfWeek(Func):
3461    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
class DayOfMonth(Func):
3464class DayOfMonth(Func):
3465    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
class DayOfYear(Func):
3468class DayOfYear(Func):
3469    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
class WeekOfYear(Func):
3472class WeekOfYear(Func):
3473    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
class LastDateOfMonth(Func):
3476class LastDateOfMonth(Func):
3477    pass
class Extract(Func):
3480class Extract(Func):
3481    arg_types = {"this": True, "expression": True}
class TimestampAdd(Func, TimeUnit):
3484class TimestampAdd(Func, TimeUnit):
3485    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampSub(Func, TimeUnit):
3488class TimestampSub(Func, TimeUnit):
3489    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampDiff(Func, TimeUnit):
3492class TimestampDiff(Func, TimeUnit):
3493    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampTrunc(Func, TimeUnit):
3496class TimestampTrunc(Func, TimeUnit):
3497    arg_types = {"this": True, "unit": True, "zone": False}
class TimeAdd(Func, TimeUnit):
3500class TimeAdd(Func, TimeUnit):
3501    arg_types = {"this": True, "expression": True, "unit": False}
class TimeSub(Func, TimeUnit):
3504class TimeSub(Func, TimeUnit):
3505    arg_types = {"this": True, "expression": True, "unit": False}
class TimeDiff(Func, TimeUnit):
3508class TimeDiff(Func, TimeUnit):
3509    arg_types = {"this": True, "expression": True, "unit": False}
class TimeTrunc(Func, TimeUnit):
3512class TimeTrunc(Func, TimeUnit):
3513    arg_types = {"this": True, "unit": True, "zone": False}
class DateFromParts(Func):
3516class DateFromParts(Func):
3517    _sql_names = ["DATEFROMPARTS"]
3518    arg_types = {"year": True, "month": True, "day": True}
class DateStrToDate(Func):
3521class DateStrToDate(Func):
3522    pass
class DateToDateStr(Func):
3525class DateToDateStr(Func):
3526    pass
class DateToDi(Func):
3529class DateToDi(Func):
3530    pass
class Day(Func):
3533class Day(Func):
3534    pass
class Decode(Func):
3537class Decode(Func):
3538    arg_types = {"this": True, "charset": True, "replace": False}
class DiToDate(Func):
3541class DiToDate(Func):
3542    pass
class Encode(Func):
3545class Encode(Func):
3546    arg_types = {"this": True, "charset": True}
class Exp(Func):
3549class Exp(Func):
3550    pass
class Explode(Func):
3553class Explode(Func):
3554    pass
class ExponentialTimeDecayedAvg(AggFunc):
3557class ExponentialTimeDecayedAvg(AggFunc):
3558    arg_types = {"this": True, "time": False, "decay": False}
class Floor(Func):
3561class Floor(Func):
3562    arg_types = {"this": True, "decimals": False}
class Greatest(Func):
3565class Greatest(Func):
3566    arg_types = {"this": True, "expressions": False}
3567    is_var_len_args = True
class GroupConcat(Func):
3570class GroupConcat(Func):
3571    arg_types = {"this": True, "separator": False}
class GroupUniqArray(AggFunc):
3574class GroupUniqArray(AggFunc):
3575    arg_types = {"this": True, "size": False}
class Hex(Func):
3578class Hex(Func):
3579    pass
class Histogram(AggFunc):
3582class Histogram(AggFunc):
3583    arg_types = {"this": True, "bins": False}
class If(Func):
3586class If(Func):
3587    arg_types = {"this": True, "true": True, "false": False}
class IfNull(Func):
3590class IfNull(Func):
3591    arg_types = {"this": True, "expression": False}
3592    _sql_names = ["IFNULL", "NVL"]
class Initcap(Func):
3595class Initcap(Func):
3596    pass
class JSONBContains(Binary):
3599class JSONBContains(Binary):
3600    _sql_names = ["JSONB_CONTAINS"]
class JSONExtract(Binary, Func):
3603class JSONExtract(Binary, Func):
3604    _sql_names = ["JSON_EXTRACT"]
class JSONExtractScalar(JSONExtract):
3607class JSONExtractScalar(JSONExtract):
3608    _sql_names = ["JSON_EXTRACT_SCALAR"]
class JSONBExtract(JSONExtract):
3611class JSONBExtract(JSONExtract):
3612    _sql_names = ["JSONB_EXTRACT"]
class JSONBExtractScalar(JSONExtract):
3615class JSONBExtractScalar(JSONExtract):
3616    _sql_names = ["JSONB_EXTRACT_SCALAR"]
class Least(Func):
3619class Least(Func):
3620    arg_types = {"expressions": False}
3621    is_var_len_args = True
class Length(Func):
3624class Length(Func):
3625    pass
class Levenshtein(Func):
3628class Levenshtein(Func):
3629    arg_types = {
3630        "this": True,
3631        "expression": False,
3632        "ins_cost": False,
3633        "del_cost": False,
3634        "sub_cost": False,
3635    }
class Ln(Func):
3638class Ln(Func):
3639    pass
class Log(Func):
3642class Log(Func):
3643    arg_types = {"this": True, "expression": False}
class Log2(Func):
3646class Log2(Func):
3647    pass
class Log10(Func):
3650class Log10(Func):
3651    pass
class LogicalOr(AggFunc):
3654class LogicalOr(AggFunc):
3655    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
class LogicalAnd(AggFunc):
3658class LogicalAnd(AggFunc):
3659    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
class Lower(Func):
3662class Lower(Func):
3663    _sql_names = ["LOWER", "LCASE"]
class Map(Func):
3666class Map(Func):
3667    arg_types = {"keys": False, "values": False}
class VarMap(Func):
3670class VarMap(Func):
3671    arg_types = {"keys": True, "values": True}
3672    is_var_len_args = True
class Matches(Func):
3675class Matches(Func):
3676    """Oracle/Snowflake decode.
3677    https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions040.htm
3678    Pattern matching MATCHES(value, search1, result1, ...searchN, resultN, else)
3679    """
3680
3681    arg_types = {"this": True, "expressions": True}
3682    is_var_len_args = True

Oracle/Snowflake decode. https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions040.htm Pattern matching MATCHES(value, search1, result1, ...searchN, resultN, else)

class Max(AggFunc):
3685class Max(AggFunc):
3686    arg_types = {"this": True, "expressions": False}
3687    is_var_len_args = True
class Min(AggFunc):
3690class Min(AggFunc):
3691    arg_types = {"this": True, "expressions": False}
3692    is_var_len_args = True
class Month(Func):
3695class Month(Func):
3696    pass
class Nvl2(Func):
3699class Nvl2(Func):
3700    arg_types = {"this": True, "true": True, "false": False}
class Posexplode(Func):
3703class Posexplode(Func):
3704    pass
class Pow(Binary, Func):
3707class Pow(Binary, Func):
3708    _sql_names = ["POWER", "POW"]
class PercentileCont(AggFunc):
3711class PercentileCont(AggFunc):
3712    pass
class PercentileDisc(AggFunc):
3715class PercentileDisc(AggFunc):
3716    pass
class Quantile(AggFunc):
3719class Quantile(AggFunc):
3720    arg_types = {"this": True, "quantile": True}
class Quantiles(AggFunc):
3725class Quantiles(AggFunc):
3726    arg_types = {"parameters": True, "expressions": True}
3727    is_var_len_args = True
class QuantileIf(AggFunc):
3730class QuantileIf(AggFunc):
3731    arg_types = {"parameters": True, "expressions": True}
class ApproxQuantile(Quantile):
3734class ApproxQuantile(Quantile):
3735    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
class RangeN(Func):
3738class RangeN(Func):
3739    arg_types = {"this": True, "expressions": True, "each": False}
class ReadCSV(Func):
3742class ReadCSV(Func):
3743    _sql_names = ["READ_CSV"]
3744    is_var_len_args = True
3745    arg_types = {"this": True, "expressions": False}
class Reduce(Func):
3748class Reduce(Func):
3749    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
class RegexpExtract(Func):
3752class RegexpExtract(Func):
3753    arg_types = {
3754        "this": True,
3755        "expression": True,
3756        "position": False,
3757        "occurrence": False,
3758        "group": False,
3759    }
class RegexpLike(Func):
3762class RegexpLike(Func):
3763    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpILike(Func):
3766class RegexpILike(Func):
3767    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpSplit(Func):
3770class RegexpSplit(Func):
3771    arg_types = {"this": True, "expression": True}
class Repeat(Func):
3774class Repeat(Func):
3775    arg_types = {"this": True, "times": True}
class Round(Func):
3778class Round(Func):
3779    arg_types = {"this": True, "decimals": False}
class RowNumber(Func):
3782class RowNumber(Func):
3783    arg_types: t.Dict[str, t.Any] = {}
class SafeDivide(Func):
3786class SafeDivide(Func):
3787    arg_types = {"this": True, "expression": True}
class SetAgg(AggFunc):
3790class SetAgg(AggFunc):
3791    pass
class SortArray(Func):
3794class SortArray(Func):
3795    arg_types = {"this": True, "asc": False}
class Split(Func):
3798class Split(Func):
3799    arg_types = {"this": True, "expression": True, "limit": False}
class Substring(Func):
3804class Substring(Func):
3805    arg_types = {"this": True, "start": False, "length": False}
class StrPosition(Func):
3808class StrPosition(Func):
3809    arg_types = {
3810        "this": True,
3811        "substr": True,
3812        "position": False,
3813        "instance": False,
3814    }
class StrToDate(Func):
3817class StrToDate(Func):
3818    arg_types = {"this": True, "format": True}
class StrToTime(Func):
3821class StrToTime(Func):
3822    arg_types = {"this": True, "format": True}
class StrToUnix(Func):
3827class StrToUnix(Func):
3828    arg_types = {"this": False, "format": False}
class NumberToStr(Func):
3831class NumberToStr(Func):
3832    arg_types = {"this": True, "format": True}
class Struct(Func):
3835class Struct(Func):
3836    arg_types = {"expressions": True}
3837    is_var_len_args = True
class StructExtract(Func):
3840class StructExtract(Func):
3841    arg_types = {"this": True, "expression": True}
class Sum(AggFunc):
3844class Sum(AggFunc):
3845    pass
class Sqrt(Func):
3848class Sqrt(Func):
3849    pass
class Stddev(AggFunc):
3852class Stddev(AggFunc):
3853    pass
class StddevPop(AggFunc):
3856class StddevPop(AggFunc):
3857    pass
class StddevSamp(AggFunc):
3860class StddevSamp(AggFunc):
3861    pass
class TimeToStr(Func):
3864class TimeToStr(Func):
3865    arg_types = {"this": True, "format": True}
class TimeToTimeStr(Func):
3868class TimeToTimeStr(Func):
3869    pass
class TimeToUnix(Func):
3872class TimeToUnix(Func):
3873    pass
class TimeStrToDate(Func):
3876class TimeStrToDate(Func):
3877    pass
class TimeStrToTime(Func):
3880class TimeStrToTime(Func):
3881    pass
class TimeStrToUnix(Func):
3884class TimeStrToUnix(Func):
3885    pass
class Trim(Func):
3888class Trim(Func):
3889    arg_types = {
3890        "this": True,
3891        "expression": False,
3892        "position": False,
3893        "collation": False,
3894    }
class TsOrDsAdd(Func, TimeUnit):
3897class TsOrDsAdd(Func, TimeUnit):
3898    arg_types = {"this": True, "expression": True, "unit": False}
class TsOrDsToDateStr(Func):
3901class TsOrDsToDateStr(Func):
3902    pass
class TsOrDsToDate(Func):
3905class TsOrDsToDate(Func):
3906    arg_types = {"this": True, "format": False}
class TsOrDiToDi(Func):
3909class TsOrDiToDi(Func):
3910    pass
class Unhex(Func):
3913class Unhex(Func):
3914    pass
class UnixToStr(Func):
3917class UnixToStr(Func):
3918    arg_types = {"this": True, "format": False}
class UnixToTime(Func):
3923class UnixToTime(Func):
3924    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
3925
3926    SECONDS = Literal.string("seconds")
3927    MILLIS = Literal.string("millis")
3928    MICROS = Literal.string("micros")
class UnixToTimeStr(Func):
3931class UnixToTimeStr(Func):
3932    pass
class Upper(Func):
3935class Upper(Func):
3936    _sql_names = ["UPPER", "UCASE"]
class Variance(AggFunc):
3939class Variance(AggFunc):
3940    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
class VariancePop(AggFunc):
3943class VariancePop(AggFunc):
3944    _sql_names = ["VARIANCE_POP", "VAR_POP"]
class Week(Func):
3947class Week(Func):
3948    arg_types = {"this": True, "mode": False}
class XMLTable(Func):
3951class XMLTable(Func):
3952    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
class Year(Func):
3955class Year(Func):
3956    pass
class Use(Expression):
3959class Use(Expression):
3960    arg_types = {"this": True, "kind": False}
class Merge(Expression):
3963class Merge(Expression):
3964    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
class When(Func):
3967class When(Func):
3968    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
def maybe_parse( sql_or_expression: Union[str, sqlglot.expressions.Expression], *, into: Union[str, Type[sqlglot.expressions.Expression], Collection[Union[str, Type[sqlglot.expressions.Expression]]], NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, prefix: Optional[str] = None, copy: bool = False, **opts) -> sqlglot.expressions.Expression:
3996def maybe_parse(
3997    sql_or_expression: ExpOrStr,
3998    *,
3999    into: t.Optional[IntoType] = None,
4000    dialect: DialectType = None,
4001    prefix: t.Optional[str] = None,
4002    copy: bool = False,
4003    **opts,
4004) -> Expression:
4005    """Gracefully handle a possible string or expression.
4006
4007    Example:
4008        >>> maybe_parse("1")
4009        (LITERAL this: 1, is_string: False)
4010        >>> maybe_parse(to_identifier("x"))
4011        (IDENTIFIER this: x, quoted: False)
4012
4013    Args:
4014        sql_or_expression: the SQL code string or an expression
4015        into: the SQLGlot Expression to parse into
4016        dialect: the dialect used to parse the input expressions (in the case that an
4017            input expression is a SQL string).
4018        prefix: a string to prefix the sql with before it gets parsed
4019            (automatically includes a space)
4020        copy: whether or not to copy the expression.
4021        **opts: other options to use to parse the input expressions (again, in the case
4022            that an input expression is a SQL string).
4023
4024    Returns:
4025        Expression: the parsed or given expression.
4026    """
4027    if isinstance(sql_or_expression, Expression):
4028        if copy:
4029            return sql_or_expression.copy()
4030        return sql_or_expression
4031
4032    import sqlglot
4033
4034    sql = str(sql_or_expression)
4035    if prefix:
4036        sql = f"{prefix} {sql}"
4037    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)

Gracefully handle a possible string or expression.

Example:
>>> maybe_parse("1")
(LITERAL this: 1, is_string: False)
>>> maybe_parse(to_identifier("x"))
(IDENTIFIER this: x, quoted: False)
Arguments:
  • sql_or_expression: the SQL code string or an expression
  • into: the SQLGlot Expression to parse into
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • prefix: a string to prefix the sql with before it gets parsed (automatically includes a space)
  • copy: whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Expression: the parsed or given expression.

def union(left, right, distinct=True, dialect=None, **opts):
4183def union(left, right, distinct=True, dialect=None, **opts):
4184    """
4185    Initializes a syntax tree from one UNION expression.
4186
4187    Example:
4188        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4189        'SELECT * FROM foo UNION SELECT * FROM bla'
4190
4191    Args:
4192        left (str | Expression): the SQL code string corresponding to the left-hand side.
4193            If an `Expression` instance is passed, it will be used as-is.
4194        right (str | Expression): the SQL code string corresponding to the right-hand side.
4195            If an `Expression` instance is passed, it will be used as-is.
4196        distinct (bool): set the DISTINCT flag if and only if this is true.
4197        dialect (str): the dialect used to parse the input expression.
4198        opts (kwargs): other options to use to parse the input expressions.
4199    Returns:
4200        Union: the syntax tree for the UNION expression.
4201    """
4202    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4203    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4204
4205    return Union(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one UNION expression.

Example:
>>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • left (str | Expression): the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right (str | Expression): the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Union: the syntax tree for the UNION expression.

def intersect(left, right, distinct=True, dialect=None, **opts):
4208def intersect(left, right, distinct=True, dialect=None, **opts):
4209    """
4210    Initializes a syntax tree from one INTERSECT expression.
4211
4212    Example:
4213        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4214        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4215
4216    Args:
4217        left (str | Expression): the SQL code string corresponding to the left-hand side.
4218            If an `Expression` instance is passed, it will be used as-is.
4219        right (str | Expression): the SQL code string corresponding to the right-hand side.
4220            If an `Expression` instance is passed, it will be used as-is.
4221        distinct (bool): set the DISTINCT flag if and only if this is true.
4222        dialect (str): the dialect used to parse the input expression.
4223        opts (kwargs): other options to use to parse the input expressions.
4224    Returns:
4225        Intersect: the syntax tree for the INTERSECT expression.
4226    """
4227    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4228    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4229
4230    return Intersect(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one INTERSECT expression.

Example:
>>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • left (str | Expression): the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right (str | Expression): the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Intersect: the syntax tree for the INTERSECT expression.

def except_(left, right, distinct=True, dialect=None, **opts):
4233def except_(left, right, distinct=True, dialect=None, **opts):
4234    """
4235    Initializes a syntax tree from one EXCEPT expression.
4236
4237    Example:
4238        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4239        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4240
4241    Args:
4242        left (str | Expression): the SQL code string corresponding to the left-hand side.
4243            If an `Expression` instance is passed, it will be used as-is.
4244        right (str | Expression): the SQL code string corresponding to the right-hand side.
4245            If an `Expression` instance is passed, it will be used as-is.
4246        distinct (bool): set the DISTINCT flag if and only if this is true.
4247        dialect (str): the dialect used to parse the input expression.
4248        opts (kwargs): other options to use to parse the input expressions.
4249    Returns:
4250        Except: the syntax tree for the EXCEPT statement.
4251    """
4252    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4253    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4254
4255    return Except(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one EXCEPT expression.

Example:
>>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • left (str | Expression): the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right (str | Expression): the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Except: the syntax tree for the EXCEPT statement.

def select( *expressions: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
4258def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4259    """
4260    Initializes a syntax tree from one or multiple SELECT expressions.
4261
4262    Example:
4263        >>> select("col1", "col2").from_("tbl").sql()
4264        'SELECT col1, col2 FROM tbl'
4265
4266    Args:
4267        *expressions: the SQL code string to parse as the expressions of a
4268            SELECT statement. If an Expression instance is passed, this is used as-is.
4269        dialect: the dialect used to parse the input expressions (in the case that an
4270            input expression is a SQL string).
4271        **opts: other options to use to parse the input expressions (again, in the case
4272            that an input expression is a SQL string).
4273
4274    Returns:
4275        Select: the syntax tree for the SELECT statement.
4276    """
4277    return Select().select(*expressions, dialect=dialect, **opts)

Initializes a syntax tree from one or multiple SELECT expressions.

Example:
>>> select("col1", "col2").from_("tbl").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expressions: the SQL code string to parse as the expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def from_(*expressions, dialect=None, **opts) -> sqlglot.expressions.Select:
4280def from_(*expressions, dialect=None, **opts) -> Select:
4281    """
4282    Initializes a syntax tree from a FROM expression.
4283
4284    Example:
4285        >>> from_("tbl").select("col1", "col2").sql()
4286        'SELECT col1, col2 FROM tbl'
4287
4288    Args:
4289        *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a
4290            SELECT statement. If an Expression instance is passed, this is used as-is.
4291        dialect (str): the dialect used to parse the input expression (in the case that the
4292            input expression is a SQL string).
4293        **opts: other options to use to parse the input expressions (again, in the case
4294            that the input expression is a SQL string).
4295
4296    Returns:
4297        Select: the syntax tree for the SELECT statement.
4298    """
4299    return Select().from_(*expressions, dialect=dialect, **opts)

Initializes a syntax tree from a FROM expression.

Example:
>>> from_("tbl").select("col1", "col2").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def update( table: str | sqlglot.expressions.Table, properties: dict, where: Union[str, sqlglot.expressions.Expression, NoneType] = None, from_: Union[str, sqlglot.expressions.Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Update:
4302def update(
4303    table: str | Table,
4304    properties: dict,
4305    where: t.Optional[ExpOrStr] = None,
4306    from_: t.Optional[ExpOrStr] = None,
4307    dialect: DialectType = None,
4308    **opts,
4309) -> Update:
4310    """
4311    Creates an update statement.
4312
4313    Example:
4314        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
4315        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
4316
4317    Args:
4318        *properties: dictionary of properties to set which are
4319            auto converted to sql objects eg None -> NULL
4320        where: sql conditional parsed into a WHERE statement
4321        from_: sql statement parsed into a FROM statement
4322        dialect: the dialect used to parse the input expressions.
4323        **opts: other options to use to parse the input expressions.
4324
4325    Returns:
4326        Update: the syntax tree for the UPDATE statement.
4327    """
4328    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
4329    update_expr.set(
4330        "expressions",
4331        [
4332            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
4333            for k, v in properties.items()
4334        ],
4335    )
4336    if from_:
4337        update_expr.set(
4338            "from",
4339            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
4340        )
4341    if isinstance(where, Condition):
4342        where = Where(this=where)
4343    if where:
4344        update_expr.set(
4345            "where",
4346            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
4347        )
4348    return update_expr

Creates an update statement.

Example:
>>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
"UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
Arguments:
  • *properties: dictionary of properties to set which are auto converted to sql objects eg None -> NULL
  • where: sql conditional parsed into a WHERE statement
  • from_: sql statement parsed into a FROM statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Update: the syntax tree for the UPDATE statement.

def delete( table: Union[str, sqlglot.expressions.Expression], where: Union[str, sqlglot.expressions.Expression, NoneType] = None, returning: Union[str, sqlglot.expressions.Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Delete:
4351def delete(
4352    table: ExpOrStr,
4353    where: t.Optional[ExpOrStr] = None,
4354    returning: t.Optional[ExpOrStr] = None,
4355    dialect: DialectType = None,
4356    **opts,
4357) -> Delete:
4358    """
4359    Builds a delete statement.
4360
4361    Example:
4362        >>> delete("my_table", where="id > 1").sql()
4363        'DELETE FROM my_table WHERE id > 1'
4364
4365    Args:
4366        where: sql conditional parsed into a WHERE statement
4367        returning: sql conditional parsed into a RETURNING statement
4368        dialect: the dialect used to parse the input expressions.
4369        **opts: other options to use to parse the input expressions.
4370
4371    Returns:
4372        Delete: the syntax tree for the DELETE statement.
4373    """
4374    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
4375    if where:
4376        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
4377    if returning:
4378        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
4379    return delete_expr

Builds a delete statement.

Example:
>>> delete("my_table", where="id > 1").sql()
'DELETE FROM my_table WHERE id > 1'
Arguments:
  • where: sql conditional parsed into a WHERE statement
  • returning: sql conditional parsed into a RETURNING statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Delete: the syntax tree for the DELETE statement.

def condition(expression, dialect=None, **opts) -> sqlglot.expressions.Condition:
4382def condition(expression, dialect=None, **opts) -> Condition:
4383    """
4384    Initialize a logical condition expression.
4385
4386    Example:
4387        >>> condition("x=1").sql()
4388        'x = 1'
4389
4390        This is helpful for composing larger logical syntax trees:
4391        >>> where = condition("x=1")
4392        >>> where = where.and_("y=1")
4393        >>> Select().from_("tbl").select("*").where(where).sql()
4394        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
4395
4396    Args:
4397        *expression (str | Expression): the SQL code string to parse.
4398            If an Expression instance is passed, this is used as-is.
4399        dialect (str): the dialect used to parse the input expression (in the case that the
4400            input expression is a SQL string).
4401        **opts: other options to use to parse the input expressions (again, in the case
4402            that the input expression is a SQL string).
4403
4404    Returns:
4405        Condition: the expression
4406    """
4407    return maybe_parse(  # type: ignore
4408        expression,
4409        into=Condition,
4410        dialect=dialect,
4411        **opts,
4412    )

Initialize a logical condition expression.

Example:
>>> condition("x=1").sql()
'x = 1'

This is helpful for composing larger logical syntax trees:

>>> where = condition("x=1")
>>> where = where.and_("y=1")
>>> Select().from_("tbl").select("*").where(where).sql()
'SELECT * FROM tbl WHERE x = 1 AND y = 1'
Arguments:
  • *expression (str | Expression): the SQL code string to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

Condition: the expression

def and_(*expressions, dialect=None, **opts) -> sqlglot.expressions.And:
4415def and_(*expressions, dialect=None, **opts) -> And:
4416    """
4417    Combine multiple conditions with an AND logical operator.
4418
4419    Example:
4420        >>> and_("x=1", and_("y=1", "z=1")).sql()
4421        'x = 1 AND (y = 1 AND z = 1)'
4422
4423    Args:
4424        *expressions (str | Expression): the SQL code strings to parse.
4425            If an Expression instance is passed, this is used as-is.
4426        dialect (str): the dialect used to parse the input expression.
4427        **opts: other options to use to parse the input expressions.
4428
4429    Returns:
4430        And: the new condition
4431    """
4432    return _combine(expressions, And, dialect, **opts)

Combine multiple conditions with an AND logical operator.

Example:
>>> and_("x=1", and_("y=1", "z=1")).sql()
'x = 1 AND (y = 1 AND z = 1)'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

And: the new condition

def or_(*expressions, dialect=None, **opts) -> sqlglot.expressions.Or:
4435def or_(*expressions, dialect=None, **opts) -> Or:
4436    """
4437    Combine multiple conditions with an OR logical operator.
4438
4439    Example:
4440        >>> or_("x=1", or_("y=1", "z=1")).sql()
4441        'x = 1 OR (y = 1 OR z = 1)'
4442
4443    Args:
4444        *expressions (str | Expression): the SQL code strings to parse.
4445            If an Expression instance is passed, this is used as-is.
4446        dialect (str): the dialect used to parse the input expression.
4447        **opts: other options to use to parse the input expressions.
4448
4449    Returns:
4450        Or: the new condition
4451    """
4452    return _combine(expressions, Or, dialect, **opts)

Combine multiple conditions with an OR logical operator.

Example:
>>> or_("x=1", or_("y=1", "z=1")).sql()
'x = 1 OR (y = 1 OR z = 1)'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Or: the new condition

def not_(expression, dialect=None, **opts) -> sqlglot.expressions.Not:
4455def not_(expression, dialect=None, **opts) -> Not:
4456    """
4457    Wrap a condition with a NOT operator.
4458
4459    Example:
4460        >>> not_("this_suit='black'").sql()
4461        "NOT this_suit = 'black'"
4462
4463    Args:
4464        expression (str | Expression): the SQL code strings to parse.
4465            If an Expression instance is passed, this is used as-is.
4466        dialect (str): the dialect used to parse the input expression.
4467        **opts: other options to use to parse the input expressions.
4468
4469    Returns:
4470        Not: the new condition
4471    """
4472    this = condition(
4473        expression,
4474        dialect=dialect,
4475        **opts,
4476    )
4477    return Not(this=_wrap_operator(this))

Wrap a condition with a NOT operator.

Example:
>>> not_("this_suit='black'").sql()
"NOT this_suit = 'black'"
Arguments:
  • expression (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Not: the new condition

def paren(expression) -> sqlglot.expressions.Paren:
4480def paren(expression) -> Paren:
4481    return Paren(this=expression)
def to_identifier(name, quoted=None):
4497def to_identifier(name, quoted=None):
4498    """Builds an identifier.
4499
4500    Args:
4501        name: The name to turn into an identifier.
4502        quoted: Whether or not force quote the identifier.
4503
4504    Returns:
4505        The identifier ast node.
4506    """
4507
4508    if name is None:
4509        return None
4510
4511    if isinstance(name, Identifier):
4512        identifier = name
4513    elif isinstance(name, str):
4514        identifier = Identifier(
4515            this=name,
4516            quoted=not re.match(SAFE_IDENTIFIER_RE, name) if quoted is None else quoted,
4517        )
4518    else:
4519        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
4520    return identifier

Builds an identifier.

Arguments:
  • name: The name to turn into an identifier.
  • quoted: Whether or not force quote the identifier.
Returns:

The identifier ast node.

def to_interval( interval: str | sqlglot.expressions.Literal) -> sqlglot.expressions.Interval:
4526def to_interval(interval: str | Literal) -> Interval:
4527    """Builds an interval expression from a string like '1 day' or '5 months'."""
4528    if isinstance(interval, Literal):
4529        if not interval.is_string:
4530            raise ValueError("Invalid interval string.")
4531
4532        interval = interval.this
4533
4534    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
4535
4536    if not interval_parts:
4537        raise ValueError("Invalid interval string.")
4538
4539    return Interval(
4540        this=Literal.string(interval_parts.group(1)),
4541        unit=Var(this=interval_parts.group(2)),
4542    )

Builds an interval expression from a string like '1 day' or '5 months'.

def to_table( sql_path: Union[str, sqlglot.expressions.Table, NoneType], **kwargs) -> Optional[sqlglot.expressions.Table]:
4555def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]:
4556    """
4557    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
4558    If a table is passed in then that table is returned.
4559
4560    Args:
4561        sql_path: a `[catalog].[schema].[table]` string.
4562
4563    Returns:
4564        A table expression.
4565    """
4566    if sql_path is None or isinstance(sql_path, Table):
4567        return sql_path
4568    if not isinstance(sql_path, str):
4569        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
4570
4571    catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3))
4572    return Table(this=table_name, db=db, catalog=catalog, **kwargs)

Create a table expression from a [catalog].[schema].[table] sql path. Catalog and schema are optional. If a table is passed in then that table is returned.

Arguments:
  • sql_path: a [catalog].[schema].[table] string.
Returns:

A table expression.

def to_column( sql_path: str | sqlglot.expressions.Column, **kwargs) -> sqlglot.expressions.Column:
4575def to_column(sql_path: str | Column, **kwargs) -> Column:
4576    """
4577    Create a column from a `[table].[column]` sql path. Schema is optional.
4578
4579    If a column is passed in then that column is returned.
4580
4581    Args:
4582        sql_path: `[table].[column]` string
4583    Returns:
4584        Table: A column expression
4585    """
4586    if sql_path is None or isinstance(sql_path, Column):
4587        return sql_path
4588    if not isinstance(sql_path, str):
4589        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
4590    table_name, column_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 2))
4591    return Column(this=column_name, table=table_name, **kwargs)

Create a column from a [table].[column] sql path. Schema is optional.

If a column is passed in then that column is returned.

Arguments:
  • sql_path: [table].[column] string
Returns:

Table: A column expression

def alias_( expression: Union[str, sqlglot.expressions.Expression], alias: str | sqlglot.expressions.Identifier, table: Union[bool, Sequence[str | sqlglot.expressions.Identifier]] = False, quoted: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts):
4594def alias_(
4595    expression: ExpOrStr,
4596    alias: str | Identifier,
4597    table: bool | t.Sequence[str | Identifier] = False,
4598    quoted: t.Optional[bool] = None,
4599    dialect: DialectType = None,
4600    **opts,
4601):
4602    """Create an Alias expression.
4603
4604    Example:
4605        >>> alias_('foo', 'bar').sql()
4606        'foo AS bar'
4607
4608        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
4609        '(SELECT 1, 2) AS bar(a, b)'
4610
4611    Args:
4612        expression: the SQL code strings to parse.
4613            If an Expression instance is passed, this is used as-is.
4614        alias: the alias name to use. If the name has
4615            special characters it is quoted.
4616        table: Whether or not to create a table alias, can also be a list of columns.
4617        quoted: whether or not to quote the alias
4618        dialect: the dialect used to parse the input expression.
4619        **opts: other options to use to parse the input expressions.
4620
4621    Returns:
4622        Alias: the aliased expression
4623    """
4624    exp = maybe_parse(expression, dialect=dialect, **opts)
4625    alias = to_identifier(alias, quoted=quoted)
4626
4627    if table:
4628        table_alias = TableAlias(this=alias)
4629        exp.set("alias", table_alias)
4630
4631        if not isinstance(table, bool):
4632            for column in table:
4633                table_alias.append("columns", to_identifier(column, quoted=quoted))
4634
4635        return exp
4636
4637    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
4638    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
4639    # for the complete Window expression.
4640    #
4641    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
4642
4643    if "alias" in exp.arg_types and not isinstance(exp, Window):
4644        exp = exp.copy()
4645        exp.set("alias", alias)
4646        return exp
4647    return Alias(this=exp, alias=alias)

Create an Alias expression.

Example:
>>> alias_('foo', 'bar').sql()
'foo AS bar'
>>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
'(SELECT 1, 2) AS bar(a, b)'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias: the alias name to use. If the name has special characters it is quoted.
  • table: Whether or not to create a table alias, can also be a list of columns.
  • quoted: whether or not to quote the alias
  • dialect: the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Alias: the aliased expression

def subquery(expression, alias=None, dialect=None, **opts):
4650def subquery(expression, alias=None, dialect=None, **opts):
4651    """
4652    Build a subquery expression.
4653
4654    Example:
4655        >>> subquery('select x from tbl', 'bar').select('x').sql()
4656        'SELECT x FROM (SELECT x FROM tbl) AS bar'
4657
4658    Args:
4659        expression (str | Expression): the SQL code strings to parse.
4660            If an Expression instance is passed, this is used as-is.
4661        alias (str | Expression): the alias name to use.
4662        dialect (str): the dialect used to parse the input expression.
4663        **opts: other options to use to parse the input expressions.
4664
4665    Returns:
4666        Select: a new select with the subquery expression included
4667    """
4668
4669    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
4670    return Select().from_(expression, dialect=dialect, **opts)

Build a subquery expression.

Example:
>>> subquery('select x from tbl', 'bar').select('x').sql()
'SELECT x FROM (SELECT x FROM tbl) AS bar'
Arguments:
  • expression (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias (str | Expression): the alias name to use.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Select: a new select with the subquery expression included

def column( col: str | sqlglot.expressions.Identifier, table: Union[str, sqlglot.expressions.Identifier, NoneType] = None, schema: Union[str, sqlglot.expressions.Identifier, NoneType] = None, quoted: Optional[bool] = None) -> sqlglot.expressions.Column:
4673def column(
4674    col: str | Identifier,
4675    table: t.Optional[str | Identifier] = None,
4676    schema: t.Optional[str | Identifier] = None,
4677    quoted: t.Optional[bool] = None,
4678) -> Column:
4679    """
4680    Build a Column.
4681
4682    Args:
4683        col: column name
4684        table: table name
4685        schema: schema name
4686        quoted: whether or not to force quote each part
4687    Returns:
4688        Column: column instance
4689    """
4690    return Column(
4691        this=to_identifier(col, quoted=quoted),
4692        table=to_identifier(table, quoted=quoted),
4693        schema=to_identifier(schema, quoted=quoted),
4694    )

Build a Column.

Arguments:
  • col: column name
  • table: table name
  • schema: schema name
  • quoted: whether or not to force quote each part
Returns:

Column: column instance

def cast( expression: Union[str, sqlglot.expressions.Expression], to: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, **opts) -> sqlglot.expressions.Cast:
4697def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
4698    """Cast an expression to a data type.
4699
4700    Example:
4701        >>> cast('x + 1', 'int').sql()
4702        'CAST(x + 1 AS INT)'
4703
4704    Args:
4705        expression: The expression to cast.
4706        to: The datatype to cast to.
4707
4708    Returns:
4709        A cast node.
4710    """
4711    expression = maybe_parse(expression, **opts)
4712    return Cast(this=expression, to=DataType.build(to, **opts))

Cast an expression to a data type.

Example:
>>> cast('x + 1', 'int').sql()
'CAST(x + 1 AS INT)'
Arguments:
  • expression: The expression to cast.
  • to: The datatype to cast to.
Returns:

A cast node.

def table_( table, db=None, catalog=None, quoted=None, alias=None) -> sqlglot.expressions.Table:
4715def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table:
4716    """Build a Table.
4717
4718    Args:
4719        table (str | Expression): column name
4720        db (str | Expression): db name
4721        catalog (str | Expression): catalog name
4722
4723    Returns:
4724        Table: table instance
4725    """
4726    return Table(
4727        this=to_identifier(table, quoted=quoted),
4728        db=to_identifier(db, quoted=quoted),
4729        catalog=to_identifier(catalog, quoted=quoted),
4730        alias=TableAlias(this=to_identifier(alias)) if alias else None,
4731    )

Build a Table.

Arguments:
  • table (str | Expression): column name
  • db (str | Expression): db name
  • catalog (str | Expression): catalog name
Returns:

Table: table instance

def values( values: Iterable[Tuple[Any, ...]], alias: Optional[str] = None, columns: Union[Iterable[str], Dict[str, sqlglot.expressions.DataType], NoneType] = None) -> sqlglot.expressions.Values:
4734def values(
4735    values: t.Iterable[t.Tuple[t.Any, ...]],
4736    alias: t.Optional[str] = None,
4737    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
4738) -> Values:
4739    """Build VALUES statement.
4740
4741    Example:
4742        >>> values([(1, '2')]).sql()
4743        "VALUES (1, '2')"
4744
4745    Args:
4746        values: values statements that will be converted to SQL
4747        alias: optional alias
4748        columns: Optional list of ordered column names or ordered dictionary of column names to types.
4749         If either are provided then an alias is also required.
4750         If a dictionary is provided then the first column of the values will be casted to the expected type
4751         in order to help with type inference.
4752
4753    Returns:
4754        Values: the Values expression object
4755    """
4756    if columns and not alias:
4757        raise ValueError("Alias is required when providing columns")
4758    table_alias = (
4759        TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
4760        if columns
4761        else TableAlias(this=to_identifier(alias) if alias else None)
4762    )
4763    expressions = [convert(tup) for tup in values]
4764    if columns and isinstance(columns, dict):
4765        types = list(columns.values())
4766        expressions[0].set(
4767            "expressions",
4768            [cast(x, types[i]) for i, x in enumerate(expressions[0].expressions)],
4769        )
4770    return Values(
4771        expressions=expressions,
4772        alias=table_alias,
4773    )

Build VALUES statement.

Example:
>>> values([(1, '2')]).sql()
"VALUES (1, '2')"
Arguments:
  • values: values statements that will be converted to SQL
  • alias: optional alias
  • columns: Optional list of ordered column names or ordered dictionary of column names to types. If either are provided then an alias is also required. If a dictionary is provided then the first column of the values will be casted to the expected type in order to help with type inference.
Returns:

Values: the Values expression object

def var( name: Union[str, sqlglot.expressions.Expression, NoneType]) -> sqlglot.expressions.Var:
4776def var(name: t.Optional[ExpOrStr]) -> Var:
4777    """Build a SQL variable.
4778
4779    Example:
4780        >>> repr(var('x'))
4781        '(VAR this: x)'
4782
4783        >>> repr(var(column('x', table='y')))
4784        '(VAR this: x)'
4785
4786    Args:
4787        name: The name of the var or an expression who's name will become the var.
4788
4789    Returns:
4790        The new variable node.
4791    """
4792    if not name:
4793        raise ValueError("Cannot convert empty name into var.")
4794
4795    if isinstance(name, Expression):
4796        name = name.name
4797    return Var(this=name)

Build a SQL variable.

Example:
>>> repr(var('x'))
'(VAR this: x)'
>>> repr(var(column('x', table='y')))
'(VAR this: x)'
Arguments:
  • name: The name of the var or an expression who's name will become the var.
Returns:

The new variable node.

def rename_table( old_name: str | sqlglot.expressions.Table, new_name: str | sqlglot.expressions.Table) -> sqlglot.expressions.AlterTable:
4800def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
4801    """Build ALTER TABLE... RENAME... expression
4802
4803    Args:
4804        old_name: The old name of the table
4805        new_name: The new name of the table
4806
4807    Returns:
4808        Alter table expression
4809    """
4810    old_table = to_table(old_name)
4811    new_table = to_table(new_name)
4812    return AlterTable(
4813        this=old_table,
4814        actions=[
4815            RenameTable(this=new_table),
4816        ],
4817    )

Build ALTER TABLE... RENAME... expression

Arguments:
  • old_name: The old name of the table
  • new_name: The new name of the table
Returns:

Alter table expression

def convert(value) -> sqlglot.expressions.Expression:
4820def convert(value) -> Expression:
4821    """Convert a python value into an expression object.
4822
4823    Raises an error if a conversion is not possible.
4824
4825    Args:
4826        value (Any): a python object
4827
4828    Returns:
4829        Expression: the equivalent expression object
4830    """
4831    if isinstance(value, Expression):
4832        return value
4833    if value is None:
4834        return NULL
4835    if isinstance(value, bool):
4836        return Boolean(this=value)
4837    if isinstance(value, str):
4838        return Literal.string(value)
4839    if isinstance(value, float) and math.isnan(value):
4840        return NULL
4841    if isinstance(value, numbers.Number):
4842        return Literal.number(value)
4843    if isinstance(value, tuple):
4844        return Tuple(expressions=[convert(v) for v in value])
4845    if isinstance(value, list):
4846        return Array(expressions=[convert(v) for v in value])
4847    if isinstance(value, dict):
4848        return Map(
4849            keys=[convert(k) for k in value],
4850            values=[convert(v) for v in value.values()],
4851        )
4852    if isinstance(value, datetime.datetime):
4853        datetime_literal = Literal.string(
4854            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
4855        )
4856        return TimeStrToTime(this=datetime_literal)
4857    if isinstance(value, datetime.date):
4858        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
4859        return DateStrToDate(this=date_literal)
4860    raise ValueError(f"Cannot convert {value}")

Convert a python value into an expression object.

Raises an error if a conversion is not possible.

Arguments:
  • value (Any): a python object
Returns:

Expression: the equivalent expression object

def replace_children(expression, fun, *args, **kwargs):
4863def replace_children(expression, fun, *args, **kwargs):
4864    """
4865    Replace children of an expression with the result of a lambda fun(child) -> exp.
4866    """
4867    for k, v in expression.args.items():
4868        is_list_arg = isinstance(v, list)
4869
4870        child_nodes = v if is_list_arg else [v]
4871        new_child_nodes = []
4872
4873        for cn in child_nodes:
4874            if isinstance(cn, Expression):
4875                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
4876                    new_child_nodes.append(child_node)
4877                    child_node.parent = expression
4878                    child_node.arg_key = k
4879            else:
4880                new_child_nodes.append(cn)
4881
4882        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)

Replace children of an expression with the result of a lambda fun(child) -> exp.

def column_table_names(expression):
4885def column_table_names(expression):
4886    """
4887    Return all table names referenced through columns in an expression.
4888
4889    Example:
4890        >>> import sqlglot
4891        >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
4892        ['c', 'a']
4893
4894    Args:
4895        expression (sqlglot.Expression): expression to find table names
4896
4897    Returns:
4898        list: A list of unique names
4899    """
4900    return list(dict.fromkeys(column.table for column in expression.find_all(Column)))

Return all table names referenced through columns in an expression.

Example:
>>> import sqlglot
>>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
['c', 'a']
Arguments:
  • expression (sqlglot.Expression): expression to find table names
Returns:

list: A list of unique names

def table_name(table) -> str:
4903def table_name(table) -> str:
4904    """Get the full name of a table as a string.
4905
4906    Args:
4907        table (exp.Table | str): table expression node or string.
4908
4909    Examples:
4910        >>> from sqlglot import exp, parse_one
4911        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
4912        'a.b.c'
4913
4914    Returns:
4915        The table name.
4916    """
4917
4918    table = maybe_parse(table, into=Table)
4919
4920    if not table:
4921        raise ValueError(f"Cannot parse {table}")
4922
4923    return ".".join(
4924        part
4925        for part in (
4926            table.text("catalog"),
4927            table.text("db"),
4928            table.name,
4929        )
4930        if part
4931    )

Get the full name of a table as a string.

Arguments:
  • table (exp.Table | str): table expression node or string.
Examples:
>>> from sqlglot import exp, parse_one
>>> table_name(parse_one("select * from a.b.c").find(exp.Table))
'a.b.c'
Returns:

The table name.

def replace_tables(expression, mapping):
4934def replace_tables(expression, mapping):
4935    """Replace all tables in expression according to the mapping.
4936
4937    Args:
4938        expression (sqlglot.Expression): expression node to be transformed and replaced.
4939        mapping (Dict[str, str]): mapping of table names.
4940
4941    Examples:
4942        >>> from sqlglot import exp, parse_one
4943        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
4944        'SELECT * FROM c'
4945
4946    Returns:
4947        The mapped expression.
4948    """
4949
4950    def _replace_tables(node):
4951        if isinstance(node, Table):
4952            new_name = mapping.get(table_name(node))
4953            if new_name:
4954                return to_table(
4955                    new_name,
4956                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
4957                )
4958        return node
4959
4960    return expression.transform(_replace_tables)

Replace all tables in expression according to the mapping.

Arguments:
  • expression (sqlglot.Expression): expression node to be transformed and replaced.
  • mapping (Dict[str, str]): mapping of table names.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
'SELECT * FROM c'
Returns:

The mapped expression.

def replace_placeholders(expression, *args, **kwargs):
4963def replace_placeholders(expression, *args, **kwargs):
4964    """Replace placeholders in an expression.
4965
4966    Args:
4967        expression (sqlglot.Expression): expression node to be transformed and replaced.
4968        args: positional names that will substitute unnamed placeholders in the given order.
4969        kwargs: keyword arguments that will substitute named placeholders.
4970
4971    Examples:
4972        >>> from sqlglot import exp, parse_one
4973        >>> replace_placeholders(
4974        ...     parse_one("select * from :tbl where ? = ?"), "a", "b", tbl="foo"
4975        ... ).sql()
4976        'SELECT * FROM foo WHERE a = b'
4977
4978    Returns:
4979        The mapped expression.
4980    """
4981
4982    def _replace_placeholders(node, args, **kwargs):
4983        if isinstance(node, Placeholder):
4984            if node.name:
4985                new_name = kwargs.get(node.name)
4986                if new_name:
4987                    return to_identifier(new_name)
4988            else:
4989                try:
4990                    return to_identifier(next(args))
4991                except StopIteration:
4992                    pass
4993        return node
4994
4995    return expression.transform(_replace_placeholders, iter(args), **kwargs)

Replace placeholders in an expression.

Arguments:
  • expression (sqlglot.Expression): expression node to be transformed and replaced.
  • args: positional names that will substitute unnamed placeholders in the given order.
  • kwargs: keyword arguments that will substitute named placeholders.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_placeholders(
...     parse_one("select * from :tbl where ? = ?"), "a", "b", tbl="foo"
... ).sql()
'SELECT * FROM foo WHERE a = b'
Returns:

The mapped expression.

def expand( expression: sqlglot.expressions.Expression, sources: Dict[str, sqlglot.expressions.Subqueryable], copy=True) -> sqlglot.expressions.Expression:
4998def expand(expression: Expression, sources: t.Dict[str, Subqueryable], copy=True) -> Expression:
4999    """Transforms an expression by expanding all referenced sources into subqueries.
5000
5001    Examples:
5002        >>> from sqlglot import parse_one
5003        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5004        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5005
5006    Args:
5007        expression: The expression to expand.
5008        sources: A dictionary of name to Subqueryables.
5009        copy: Whether or not to copy the expression during transformation. Defaults to True.
5010
5011    Returns:
5012        The transformed expression.
5013    """
5014
5015    def _expand(node: Expression):
5016        if isinstance(node, Table):
5017            name = table_name(node)
5018            source = sources.get(name)
5019            if source:
5020                subquery = source.subquery(node.alias or name)
5021                subquery.comments = [f"source: {name}"]
5022                return subquery
5023        return node
5024
5025    return expression.transform(_expand, copy=copy)

Transforms an expression by expanding all referenced sources into subqueries.

Examples:
>>> from sqlglot import parse_one
>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
Arguments:
  • expression: The expression to expand.
  • sources: A dictionary of name to Subqueryables.
  • copy: Whether or not to copy the expression during transformation. Defaults to True.
Returns:

The transformed expression.

def func( name: str, *args, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.Func:
5028def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5029    """
5030    Returns a Func expression.
5031
5032    Examples:
5033        >>> func("abs", 5).sql()
5034        'ABS(5)'
5035
5036        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5037        'CAST(5 AS DOUBLE)'
5038
5039    Args:
5040        name: the name of the function to build.
5041        args: the args used to instantiate the function of interest.
5042        dialect: the source dialect.
5043        kwargs: the kwargs used to instantiate the function of interest.
5044
5045    Note:
5046        The arguments `args` and `kwargs` are mutually exclusive.
5047
5048    Returns:
5049        An instance of the function of interest, or an anonymous function, if `name` doesn't
5050        correspond to an existing `sqlglot.expressions.Func` class.
5051    """
5052    if args and kwargs:
5053        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5054
5055    from sqlglot.dialects.dialect import Dialect
5056
5057    converted = [convert(arg) for arg in args]
5058    kwargs = {key: convert(value) for key, value in kwargs.items()}
5059
5060    parser = Dialect.get_or_raise(dialect)().parser()
5061    from_args_list = parser.FUNCTIONS.get(name.upper())
5062
5063    if from_args_list:
5064        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5065    else:
5066        kwargs = kwargs or {"expressions": converted}
5067        function = Anonymous(this=name, **kwargs)
5068
5069    for error_message in function.error_messages(converted):
5070        raise ValueError(error_message)
5071
5072    return function

Returns a Func expression.

Examples:
>>> func("abs", 5).sql()
'ABS(5)'
>>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
'CAST(5 AS DOUBLE)'
Arguments:
  • name: the name of the function to build.
  • args: the args used to instantiate the function of interest.
  • dialect: the source dialect.
  • kwargs: the kwargs used to instantiate the function of interest.
Note:

The arguments args and kwargs are mutually exclusive.

Returns:

An instance of the function of interest, or an anonymous function, if name doesn't correspond to an existing sqlglot.expressions.Func class.

def true():
5075def true():
5076    """
5077    Returns a true Boolean expression.
5078    """
5079    return Boolean(this=True)

Returns a true Boolean expression.

def false():
5082def false():
5083    """
5084    Returns a false Boolean expression.
5085    """
5086    return Boolean(this=False)

Returns a false Boolean expression.

def null():
5089def null():
5090    """
5091    Returns a Null expression.
5092    """
5093    return Null()

Returns a Null expression.